Princeton1/module8/src/main/java/com/hithomelabs/princeton1/module8/HeapSort.java
hitanshu310 bbc040dcd4
All checks were successful
sample gradle build and test / build (pull_request) Successful in 2m16s
sample gradle build and test / build (push) Successful in 55s
Heapsort Implementation
2025-02-16 16:40:56 +05:30

32 lines
938 B
Java

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);
}
}
}