privatestaticvoidheapSort(int[] array){ int len = array.length - 1; for (int i = (len - 1) / 2; i >= 0; i--) { sink(array, i, len); } printArr(array); while (len >= 0) { swap(array, 0, len); sink(array, 0, --len); } }
privatestaticvoidsink(int[] array, int i, int len){ while (i * 2 + 1 <= len) { int j = i * 2 + 1; if (j + 1 <= len && array[j+1] > array[j]) j++; if (array[i] > array[j]) break; swap(array, i, j); i = j; } }
privatestaticvoidswap(int[] array, int i, int j){ int temp = array[i]; array[i] = array[j]; array[j] = temp; } publicstaticvoidmain(String[] args){ int[] array = {2, 3, 1, 6, 4, 5, 2, 1}; heapSort(array); printArr(array); }