package com.thinker.suanfa.sort;

/**
 * @author lzh
 * @apiNote 堆排序，从小到大,建立最大堆
 */
public class HeapSort {

    private static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    private static void maxHeap(int[] arr, int size, int index) {
        int left = 2 * index + 1, right = 2 * index + 2;
        int max = index;
        if (left < size && arr[left] > arr[max]) max = left;
        if (right < size && arr[right] > arr[max]) max = right;
        if (max != index) {
            swap(arr, max, index);
            maxHeap(arr, size, max);
        }
    }

    private static void buildHeap(int[] arr) {
        for (int i = arr.length / 2; i >= 0; i--) {
            maxHeap(arr, arr.length, i);
        }
    }

    private static void heapSort(int[] arr) {
        buildHeap(arr);
        for (int i = arr.length - 1; i >= 1; i--) {
            swap(arr, 0, i);
            maxHeap(arr, i, 0);
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{4, 2, 6, 8, 9, 3, 1, 5};
        long begin = System.nanoTime();
        heapSort(arr);
        long end = System.nanoTime();
        for (int a : arr) {
            System.out.print(a + "\t");
        }
        System.out.println("\nrun time:" + (double) (end - begin) / 1000 + " ms");
    }
}
