1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public class HeapOperator {
public static void upAdjust(int[] array) { int childIndex = array.length - 1; int parentIndex = (childIndex - 1) / 2; int temp = array[childIndex]; while (childIndex > 0 && temp < array[parentIndex]) { array[childIndex] = array[parentIndex]; childIndex = parentIndex; parentIndex = (parentIndex - 1) / 2; } array[childIndex] = temp; }
public static void downAdjust(int[] array, int parentIndex, int length) { int temp = array[parentIndex]; int childIndex = 2 * parentIndex + 1; while (childIndex < length) { if (childIndex + 1 < length && array[childIndex + 1] < array[childIndex]) { childIndex++; } if (temp <= array[childIndex]) break; array[parentIndex] = array[childIndex]; parentIndex = childIndex; childIndex = 2 * childIndex + 1; } array[parentIndex] = temp; }
public static void buildHeap(int[] array) { for (int i = (array.length - 2) / 2; i >= 0; i--) { downAdjust(array, i, array.length); } }
public static void main(String[] args) { int[] array = new int[]{1, 3, 2, 6, 5, 7, 8, 9, 10, 0}; upAdjust(array); System.out.println(Arrays.toString(array));
array = new int[]{7, 1, 3, 10, 5, 2, 8, 9, 6}; buildHeap(array); System.out.println(Arrays.toString(array)); } }
|