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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| private static class HeapSort { public HeapSort(int a[]) { buildMaxHeapify(a); heapSort(a); System.out.println(""); System.out.println("****4.堆排序之后:****"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + ","); } }
public static void buildMaxHeapify(int a[]) { System.out.println("字符串的长度为:" + a.length); int startIndex = getParentIndex(a.length - 1); for (int i = startIndex; i >= 0; i--) { maxHeapify(a, a.length, i); } }
private static void maxHeapify(int[] a, int length, int index) { int left = getChildLeftIndex(index); int right = getChildRightIndex(index);
int largest = index; if (left < length && a[left] > a[index]) { largest = left; } if (right < length && a[right] > a[largest]) { largest = right; } if (largest != index) { int temp = a[index]; a[index] = a[largest]; a[largest] = temp; maxHeapify(a, length, largest); } }
private static int getParentIndex(int i) { return i / 2; }
private static int getChildLeftIndex(int index) { return index * 2 + 1; }
private static int getChildRightIndex(int index) { return index * 2 + 2; }
public static void heapSort(int a[]) { for (int i = a.length - 1; i > 0; i--) { int temp = a[0]; a[0] = a[i]; a[i] = temp; maxHeapify(a, i, 0); } } }
|