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
| public class Main { public static void main(String[] args) { int a[] = {8, 2, 5, 6, 4, 8, 9, 7, 14, 2, 3, 6, 4}; a = heapSort(a); for (int i=0;i<a.length;i++){ System.out.print(a[i]+" "); } System.out.println(); } private static int[] buildMaxHeap(int[] a) { int half = (a.length - 2) / 2; for (int i = half; i >= 0; i--) { adjustDownToUp(a, i, a.length); } return a; } private static void adjustDownToUp(int[] a, int k, int length) { int temp = a[k]; for (int i = 2 * k + 1; i < length - 1; i = 2 * i + 1) { if (i < length && a[i] < a[i + 1]) { i++; } if (temp >= a[i]) { break; } else { a[k] = a[i]; k = i; } } a[k] = temp; } public static int[] heapSort(int[] array) { array = buildMaxHeap(array); for (int i = array.length - 1; i > 1; i--) { swap(array, 0, i); adjustDownToUp(array, 0, i); } return array; } public static void swap(int a[], int i, int j) { a[i] = a[i] + a[j]; a[j] = a[i] - a[j]; a[i] = a[i] - a[j]; } }
JAVA
|