标签:
Given an integer array, heapify it into a min-heap array.
1 public class Solution { 2 /** 3 * @param A: Given an integer array 4 * @return: void 5 */ 6 7 public void heapify(int[] array) { 8 int heapSize = array.length; 9 for (int i = heapSize / 2 - 1; i >= 0; i--) { 10 minHeapify(array, i, array.length); 11 } 12 } 13 14 /// MaxHeapify is to build the max heap from the ‘position‘ 15 public void minHeapify(int[] array, int position, int heapSize) 16 { 17 int left = left(position); 18 int right = right(position); 19 int minPosition = position; 20 21 if (left < heapSize && array[left] < array[position]) { 22 minPosition = left; 23 } 24 25 if (right < heapSize && array[right] < array[minPosition]) { 26 minPosition = right; 27 } 28 29 if (position != minPosition) { 30 swap(position, minPosition, array); 31 minHeapify(array, minPosition, heapSize); 32 } 33 } 34 35 public void swap(int i, int j, int[] A) { 36 int temp = A[i]; 37 A[i] = A[j]; 38 A[j] = temp; 39 } 40 41 /// return the left child position 42 public int left(int i) 43 { 44 return 2 * i + 1; 45 } 46 /// return the right child position 47 public int right(int i) 48 { 49 return 2 * i + 2; 50 } 51 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5657055.html