package com.hithomelabs.princeton1.module8;

import com.hithomelabs.princeton1.module5.AbstractCustomSorts;


public class HeapSort<E> extends AbstractCustomSorts<E> {

    @Override
    public void sort(E[] arr) {
        int N = arr.length;

        E[] heapArr = (E[]) new Object[N+1];
        // * * to simplify we copy original array from
        System.arraycopy(arr, 0, heapArr, 1, N);

        // * * An array of size N holds a heap of size N-1
        coreSortingLogic(heapArr, N);
        System.arraycopy(heapArr, 1, arr, 0, N);
    }

    private void coreSortingLogic(E[] arr, int N) {
        // * * Converting array to max-heap an array in place
        for (int i = N/2; i >= 1; i--)
            Heap.sink(arr, i, N);
        // * * After converting to max-heap, in every iteration remove the max element of the heap
        while(N > 1){
            exch(arr, 1, N--);
            Heap.sink(arr, 1, N);
        }
    }
}
