- package lhz.algorithm.chapter.six;
-
-
-
-
-
-
-
-
-
-
- * 本文地址:http://mushiqianmeng.blog.51cto.com/3970029/738164
- public class HeapSort {
-
- private static int[] input = new int[] {16, 14, 10, 8, 7, 9, 3, 2, 4, 1};
-
- public static void main(String[] args) {
-
- heapSort();
-
- printArray();
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- private static void heapSort() {
- int length = input.length;
-
- buildMaxHeap(input, length);
- for (int i = length - 1; i > 0; i--) {
- int temp = input[i];
- input[i] = input[0];
- input[0] = temp;
- maxHeapify(input, 1, i);
- }
- }
-
- private static void buildMaxHeap(int[] array, int heapSize) {
- for (int i = heapSize / 2; i > 0; i--) {
- maxHeapify(array, i, heapSize);
- }
- }
-
- private static void maxHeapify(int[] array, int index, int heapSize) {
- int l = index * 2;
- int r = l + 1;
- int largest;
-
- if (l <= heapSize && array[l-1] > array[index-1]) {
- largest = l;
- } else {
- largest = index;
- }
-
- if (r <= heapSize && array[r-1] > array[largest-1]) {
- largest = r;
- }
-
- if (largest != index) {
- int temp = array[index-1];
- array[index-1] = array[largest-1];
- array[largest-1] = temp;
- maxHeapify(array, largest, heapSize);
- }
- }
-
- private static void printArray() {
- for (int i : input) {
- System.out.print(i + " ");
- }
- }
- }

|