MaxHeapify

heap is a specialized tree-based data structure that satisfies the heap property: If A is a parent node of B then key(A) is ordered with respect to key(B) with the same ordering applying across the heap. Either the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node (this kind of heap is called max heap) or the keys of parent nodes are less than or equal to those of the children (min heap). Heaps are crucial in several efficient graph algorithms such as Dijkstra's algorithm, and in the sorting algorithm heapsort.

 //O(logn)
1
public class MaxHeapify { 2 3 private static int[] input = new int[] { 16, 4, 10, 14, 7, 9, 3, 2, 8, 1 }; 4 private static int heapSize = input.length; 5 6 public static void maxHeapify(int[] a,int index){ 7 int l=index*2; 8 int r=l+1; 9 int largest; 10 if(l<=heapSize && a[l-1]>a[index-1]){ 11 largest=l; 12 } 13 else{ 14 largest=index; 15 } 16 if(r<=heapSize && a[r-1]>a[largest-1]){ 17 largest=r; 18 } 19 if(largest != index){ 20 int temp=a[index-1]; 21 a[index-1]=a[largest-1]; 22 a[largest-1]=temp; 23 maxHeapify(a,largest); 24 } 25 26 } 27 28 public static void printArray(int[] a){ 29 for(int i = 0;i < a.length;i++){ 30 System.out.print(a[i]+" "); 31 } 32 } 33 34 public static void main(String[] args) { 35 // TODO Auto-generated method stub 36 maxHeapify(input, 2); 37 printArray(input); 38 } 39 40 }

 

posted on 2013-03-29 22:29  melotang  阅读(252)  评论(0)    收藏  举报