forked from Hithomelabs/Princeton1
47 lines
1.5 KiB
Java
47 lines
1.5 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.AbstractCustomSorts;
|
|
|
|
public class Heap{
|
|
|
|
/*
|
|
* * Sink Node T with to it's appropriate place in a Heap of size N, if it's children exist and are greater
|
|
* * 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> 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){
|
|
T temp = arr[i];
|
|
arr[i] = arr[j];
|
|
arr[j] = temp;
|
|
}
|
|
|
|
private static <T> boolean less(T v, T w){
|
|
if(((Comparable<T>)v).compareTo(w) < 1 ) return true;
|
|
else return false;
|
|
}
|
|
}
|