堆的定義如下:
n個元素的序列{k0,k1,...,ki,…,k(n-1)}當且僅當滿足下關系時,稱之為堆。
" ki<=k2i,ki<=k2i+1;或ki>=k2i,ki>=k2i+1.(i=1,2,…,[n/2])"
若將和此次序列對應的一維數組(即以一維數組作此序列的存儲結構)看成是一個完全二叉樹,
則完全二叉樹中每一個節點的值的都大於或等於任意一個字節的值(如果有的話),稱之為大頂堆。
則完全二叉樹中每一個節點的值的都小於或等於任意一個字節的值(如果有的話),稱之為小頂堆。
由此,若序列{k0,k1,…,k(n-1)}是堆,則堆頂元素(或完全二叉樹的根)必為序列中n個元素的最小值(或最大值)。
倘若給堆中每一個節點都賦予一個整數值標簽,根節點被標記為0,對於每一個標記為i的節點,其左子節點(若存在的話)被標記為2*i+1,其右子節點(若存在的話)被標記為2*i+2,對於一個標記為i的非根節點,其父節點被標記為(i-1)/2。使用這個標記,我們能夠將堆存儲在數組中,節點存儲在數據中的位置就使其標簽。
堆排序算法:
sort(A) buildHeap(A) for i=n-1 downto 1 do swap A[0] with A[i] heapify(A,0,i) end buildHeap(A) for i=n/2 - 1 downto 0 do heapify(A,i,n) end heapify(A,idx,max) left = 2*idx +1 right = 2*idx +2 if(left<max and A[left]>A[idx]) then largest = left else largest = idx if(right < max and A[right]>A[largest]) then largest = ritht if(largest!=idx) then swap A[largest] with A[idx] heapify(A,largest,max) end
堆排序的JAVA語言實現 :
package org.myorg.algorithm; public class HeapSorter { public static void heapSort(int[] array){ buildHeap(array);//構建堆 int n = array.length; int i=0; for(i=n-1;i>=1;i--){ swap(array,0,i); heapify(array,0,i); } } public static void buildHeap(int[] array){ int n = array.length;//數組中元素的個數 for(int i=n/2-1;i>=0;i--) heapify(array,i,n); } public static void heapify(int[] A,int idx,int max){ int left = 2*idx+1;// 左孩子的下標(如果存在的話) int right =2*idx+2;// 左孩子的下標(如果存在的話) int largest = 0;//尋找3個節點中最大值節點的下標 if(left<max && A[left]>A[idx]) largest = left; else largest = idx; if(right<max && A[right]>A[largest]) largest = right; if(largest!=idx){ swap(A,largest,idx); heapify(A,largest,max); } } public static void swap(int[] array,int i,int j){ int temp =0; temp=array[i]; array[i]=array[j]; array[j]=temp; } public static void main(String[] args) { int[] a = {1,2,3,4,5,6,7,16,9,10,11,12,13,14,15,8}; System.out.println("排序前.........................."); for(int i=0;i<a.length;i++) System.out.println(a[i]); heapSort(a); System.out.println("排序后.........................."); for(int i=0;i<a.length;i++) System.out.println(a[i]); } }