|
| 1 | +public class HeapSort { |
| 2 | + |
| 3 | + private static int[] array = new int[]{5, 3, 6, 4, 8, 9 , 1, 10}; |
| 4 | + |
| 5 | + public static void main(String[] args) { |
| 6 | + heapSort(); |
| 7 | + |
| 8 | + for(int i : array) { |
| 9 | + System.out.println(i); |
| 10 | + } |
| 11 | + } |
| 12 | + |
| 13 | + private static void heapSort() { |
| 14 | + int length = array.length; |
| 15 | + |
| 16 | + buildMaxHeap(array, length); |
| 17 | + for(int i = length - 1; i > 0; i--) { |
| 18 | + int temp = array[0]; |
| 19 | + array[0] = array[i]; |
| 20 | + array[i] = temp; |
| 21 | + maxHeapify(array, 1, i); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + private static void buildMaxHeap(int[] array, int heapSize) { |
| 26 | + if(array == null) { |
| 27 | + throw new NullPointerException("null"); |
| 28 | + } |
| 29 | + if(array.length <=0 || heapSize <= 0) { |
| 30 | + throw new IllegalArgumentException("illegal"); |
| 31 | + } |
| 32 | + if(heapSize > array.length) { |
| 33 | + heapSize = array.length; |
| 34 | + } |
| 35 | + |
| 36 | + for(int i = heapSize/2; i > 0; i--) { |
| 37 | + maxHeapify(array, i, heapSize); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private static void maxHeapify(int[] array, int index, int heapSize) { |
| 42 | + int l = index * 2; |
| 43 | + int r = l + 1; |
| 44 | + int largest; |
| 45 | + |
| 46 | + if(l <= heapSize && array[l - 1] > array[index - 1]) { |
| 47 | + largest = l; |
| 48 | + } else { |
| 49 | + largest = index; |
| 50 | + } |
| 51 | + |
| 52 | + if(r <= heapSize && array[r - 1] > array[largest - 1]) { |
| 53 | + largest = r; |
| 54 | + } |
| 55 | + |
| 56 | + if(largest != index) { |
| 57 | + int temp = array[index - 1]; |
| 58 | + array[index - 1] = array[largest - 1]; |
| 59 | + array[largest - 1] = temp; |
| 60 | + maxHeapify(array, largest, heapSize); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments