forked from Hithomelabs/Princeton1
Reviewed-on: Hithomelabs/Princeton1#20 Reviewed-by: hitanshu <hitanshu98@gmail.com> Co-authored-by: Kruti Shah <krutis0201@gmail.com> Co-committed-by: Kruti Shah <krutis0201@gmail.com>
45 lines
1.8 KiB
Java
45 lines
1.8 KiB
Java
package com.hithomelabs.princeton1.module8;
|
|
|
|
/*
|
|
* * Designing Heap as a wrapper class with static methods that perform sink and swim operations on underlying comparable[] array
|
|
* * Heap does not have any instance variables, instance variables shall be housed by, the implementation using heaps, like priority queues and heap sort
|
|
*/
|
|
|
|
|
|
import com.hithomelabs.princeton1.module5.MeasurableHelper;
|
|
import com.hithomelabs.princeton1.module5.SortingMetaData;
|
|
|
|
import java.util.Comparator;
|
|
|
|
public class Heap implements MeasurableHelper {
|
|
|
|
/*
|
|
* * Sink Node T with to it's appropriate place in a Heap of size N, if it's children exist and are greater
|
|
*/
|
|
public static <T> void sink(T[] arr, int root, int N, Comparator<T> cmp, SortingMetaData metaData){
|
|
// * Check if at least one child exists
|
|
while(2 * root <= N){
|
|
int j = 2 * root;
|
|
// * Check if the right child exists and is larger than the left child, if yes swap right and left child
|
|
if(j+1 <= N){
|
|
if (MeasurableHelper.less(arr[j], arr[j+1], cmp, metaData)) j++;
|
|
}
|
|
if (!MeasurableHelper.less(arr[root], arr[j], cmp, metaData)) break;
|
|
MeasurableHelper.exch(arr, root, j, metaData);
|
|
// * The root node has now sunken low, call sink recursively with new node to check if it sinks further
|
|
root = j;
|
|
}
|
|
}
|
|
|
|
// * * Swim if element is not root, and parent is lesser than node
|
|
public static <T> void swim(T[] arr, int node, int N, Comparator<T> cmp, SortingMetaData metaData){
|
|
while(node > 1){
|
|
if(! MeasurableHelper.less(arr[node/2],arr[node], cmp, metaData)) break;
|
|
MeasurableHelper.exch(arr, node, node/2, metaData);
|
|
node = node/2;
|
|
}
|
|
}
|
|
|
|
|
|
}
|