heap implementation

This commit is contained in:
Kruti Shah 2025-02-20 02:03:06 +05:30
parent e0c20341ad
commit dd369b451a
2 changed files with 21 additions and 4 deletions

View File

@ -14,10 +14,23 @@ public class Heap{
* * Implement sink API to sink a node if it's sub-heap is not heap-order
*/
public static <T> void sink(T[] arr, int root, int N){
while (N >= root*2) {
int greater_index = root * 2;
if (N >= root * 2 + 1 && less(arr[root * 2], arr[root * 2 + 1]))
greater_index += 1;
if(!less(arr[root], arr[greater_index]))
break;
exch(arr, root, greater_index);
root = greater_index;
}
}
// * * Swim if element is not root, and parent is lesser than node
public static <T extends Comparable<T>> void swim(T[] arr, int node, int N){
public static <T> void swim(T[] arr, int node){
while(node > 1 && less(arr[node/2], arr[node])){
exch(arr, node, node/2);
node = node/2;
}
}
private static <T> void exch(T[] arr, int i, int j){
@ -30,6 +43,4 @@ public class Heap{
if(((Comparable<T>)v).compareTo(w) < 1 ) return true;
else return false;
}
}

View File

@ -2,7 +2,6 @@ package com.hithomelabs.princeton1.module8;
import com.hithomelabs.princeton1.module5.AbstractCustomSorts;
public class HeapSort<E> extends AbstractCustomSorts<E> {
@Override
@ -23,5 +22,12 @@ public class HeapSort<E> extends AbstractCustomSorts<E> {
* * P.S the provision of making the index 0 null for ease of use has already been done above
*/
private void coreSortingLogic(E[] arr, int N) {
for(int n=2; n <= N; n++){
Heap.swim(arr, n);
}
while (N > 1){
exch(arr, 1, N--);
Heap.sink(arr, 1, N);
}
}
}