本文主要是介绍堆排序 快排,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
堆排序关系
parent = (i-1) / 2
left = 2i + 1
right = 2i+2
public class HeapSort {public static void main(String []args){int tree [] = {10,3,4,9,11};int n = 5;heapSort(tree,n);for (int i : tree){System.out.println(i);}}static void heapSort(int tree[],int n){buildHeap(tree,n);int i ;//首尾交换for (i = n - 1; i >= 0; i--){swap(tree,i,0);heapify(tree,i,0);}}static void buildHeap(int tree[],int n){int lastNode = n-1;int parent = (lastNode - 1) / 2 ;//父节点int i ;for (i = parent; i >= 0 ; i--){heapify(tree,n,i);}}static void heapify(int tree[], int n, int i) {if (i >= n) return;int left = 2 * i + 1; //左树位置int right = 2 * i + 2; //右树位置int max = i;if (left < n && tree[left] > tree[max]) {max = left;}if (right < n && tree[right] > tree[max]) {max = right;}if (max != i) {swap(tree, max, i);heapify(tree, n, max);}}static void swap(int arr[], int i, int j) {int temp = arr[i];arr[i] = arr[j];arr[j] = temp;}
}
package com;import com.alibaba.fastjson.JSONObject;public class QuickSort {static void partition(int a[], int low, int high) {if (low >= high) return;int pivot = a[low], i = low, j = high;while (i < j) {while (i < j && a[j] > pivot) --j;if (i < j) a[i++] = a[j];while (i < j && a[i] <= pivot) ++i;if (i < j) a[j--] = a[i];}a[i] = pivot;partition(a, low, i - 1);partition(a, i + 1, high);}public static void main(String[] args) {int[] data = {2, 3, 1, 7, 5};partition(data, 0, 4);System.out.println(JSONObject.toJSON(data));}
}
这篇关于堆排序 快排的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!