Skip to content

Instantly share code, notes, and snippets.

@ankurbansal
Last active August 29, 2015 14:24
Show Gist options
  • Save ankurbansal/768629e753ebee763222 to your computer and use it in GitHub Desktop.
Save ankurbansal/768629e753ebee763222 to your computer and use it in GitHub Desktop.
Java Heap
abstract class Heap{
int [] heap=null;
int heapSize=0;
public int getCount();
public int getTop() {
return heap[1];
}
public abstract int removeTop();
public abstract int addLast(int value);
public void printHeap(){
int temp=1;
while (temp <= heapSize) {
System.out.print(" "+ heap[temp++]);
}
System.out.println(" ");
}
}
class MaxHeap extends Heap{
public MaxHeap(int i ){
heap= new int[i+1]; // as leaving the first point empty
}
public int getCount() {
return heapSize;
}
public int removeTop() {
int i=1;
int headValue= heap[i];
heap[i]= heap[heapSize];
heap[heapSize]=0;
heapSize--;
while(i<=(heapSize/2)){
int high=0;
if(heap[2*i]>heap[2*i+1]){
high=2*i;
}else{
high=2*i+1;
}
if (heap[high]>heap[i]){
int temp=heap[i];
heap[i]=heap[high];
heap[high]=temp;
i=high;
}else{
return headValue;
}
}
return headValue;
}
public int addLast(int newNode) {
int i=++heapSize;
heap[i]=newNode;
while(i>1){
if(heap[i]>heap[i/2]){
int temp=heap[i];
heap[i]=heap[i/2];
heap[i/2]=temp;
i=i/2;
}else{
return i;
}
}
return heapSize;
}
}
class MinHeap extends Heap{
public MinHeap(int i){
heap=new int [i+1];
}
public int getCount() {
return heapSize;
}
public int removeTop() {
int item=heap[1];
int temp=heap[heapSize];
heapSize--;
int parent=1;
int child=2;
while(child<=heapSize){
if(child<heapSize && (heap[child]>heap[child+1])){
child++;
}
if(temp<heap[child]) break;
heap[parent]=heap[child];
parent=child;
child=child*2;
}
heap[parent]=temp;
return item;
}
public int addLast(int item) {
if (heapSize==heap.length){
System.out.println("Heap is already full");return -1;
}
int index=heapSize+1;
while(index!=1){
if(item<heap[index/2]){
heap[index]=heap[index/2];
index=index/2;
}else{break;}
}
heap[index]=item;
heapSize=heapSize+1;
return index;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment