1、堆的性质:堆是一种数组,但是以树的结构形式来看待它,如下标 i 节点的求解Parent和Children节点如下:
PARENT(i)
return ⌊i/2⌋
LEFT(i)
return 2i
RIGHT(i)
return 2i + 1
最大堆:根以外的每个结点i都不大于其根结点,即根为最大元素,在顶端,有A[PARENT(i)] (根)≥ A[i]
最小堆:根以外的每个结点i都不小于其根结点,即根为最小元素,在顶端,有A[PARENT(i)] (根)≤ A[i]
堆排序时间复杂度:O(nlogn)
2、堆的维持 (nlogn):
MAX-HEAPIFY(A, i) 1 l ← LEFT(i) 2 r ← RIGHT(i) 3 if l ≤ heap-size[A] and A[l] > A[i] 4 then largest ← l 5 else largest ← i 6 if r ≤ heap-size[A] and A[r] > A[largest] 7 then largest ← r 8 if largest ≠ i 9 then exchange A[i] ↔ A[largest] 10 MAX-HEAPIFY(A, largest)
3、建堆:不断调用 MAX-HEAPIFY函数来建堆BUILD-MAX-HEAP(A) 1 heap-size[A] ← length[A] 2 for i ← ⌊length[A]/2⌋ downto 1 3 do MAX-HEAPIFY(A, i)
4、堆排序:首先是把一个给定的数组变成MAX堆,然后把根节点和堆的最后一个交换,堆的大小减1,再调整堆,这样下去,直到堆的大小为1: 伪代码如下:HEAPSORT(A) 1 BUILD-MAX-HEAP(A) 2 for i ← length[A] downto 2 3 do exchange A[1] ↔ A[i] 4 heap-size[A] ← heap-size[A] - 1 5 MAX-HEAPIFY(A, 1)
堆排序的图解过程如下:5、Java源代码:另一个版本Java Code:package Sort; public class HeapSort { //Private variable to record the size of heap private static int heapSize; //Heap sort method public static float[] HeapSortAlgorithm(float flt[], int length){ Build_Max_Heap(flt, length); for(int i=length-1;i>0;i--){ Swap(flt, 0, i); heapSize--; Max_Heapify(flt, 0); } return flt; } //Build the max heap from input array public static void Build_Max_Heap(float flt[], int length){ heapSize=length; for (int i=(length-1)/2;i>=0;i--) { Max_Heapify(flt, i); } } //Adjust the position of elements in the array to satisfy the max heap private static void Max_Heapify(float flt[], int i){ int leftChild=2*i+1; int rightChild=2*i+2; int largest=i; if (leftChild<heapSize&&flt[leftChild]>flt[i]) { largest=leftChild; } if (rightChild<heapSize&&flt[rightChild]>flt[largest]) { largest=rightChild; } if (largest!=i) { Swap(flt, largest, i); Max_Heapify(flt, largest); } } //Swap the values of two elements in the array private static void Swap(float flt[], int left, int right){ float temp=flt[left]; flt[left]=flt[right]; flt[right]=temp; } }
public class HeapTest { /** * @param args */ public static void buildHeap(int arr[],int startIndex, int range) { int value = arr[startIndex]; int large = startIndex*2+1; while(large <= range) { if(large < range && arr[large]>arr[large+1]) { large++; } if(arr[large]<value) { arr[startIndex] = arr[large]; arr[large] = value; startIndex = large; large = startIndex*2+1; } else { break; } } } public static void HeapSort(int arr[],int start, int end) { for(int i=end/2;i>=0;i--) { buildHeap(arr, i, end-1); } int endTemp = end; for(int i=0;i<endTemp;i++) { System.out.println(arr[0]); arr[0] = arr[end - 1]; buildHeap(arr, 0, end -1); end--; } } public static void main(String[] args) { // TODO Auto-generated method stub int nums[] = {9,8,7,6,5,4,3,2,1,0}; HeapSort(nums, 0, 10); } }
参考:http://blog.csdn.net/v_JULY_v/article/details/6198644
http://blog.csdn.net/dremi/article/details/1824099