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
| void heapSort(int[] arr) { int len = arr.length; buildMaxHeap(arr, len); for (int i = len - 1; i > 0; i--) { swap(arr, i, 0); len--; adjustHeap(arr, 0, len); } }
void buildMaxHeap(int[] arr, int len) { for (int i = len >> 1; i >= 0; i--) { adjustHeap(arr, i, len); } }
void adjustHeap(int[] arr, int i, int len) { int left = i * 2 + 1; int right = i * 2 + 2; int max = i; if (left < len && arr[left] > arr[max]) { max = left; } if (right < len && arr[right] > arr[max]) { max = right; } if (i != max) { swap(arr, i, max); adjustHeap(arr, max, len); } }
void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }
|