Max Heap In java

Max heap is a property of heap in this max element will be stored on the top.
I am using array to create max heap here.
Heap is a complete binary tree and add new element to last leaf of the tree and it starts filling tree from left to right.

So when will add new element to heap it will be added to last index then will use heapifyUp method to check either last element is in correct place or not means all the parent node of the new element should be larger then this. So using this always we will be having largest element on top of tree( root node or 0th index of array).

To remove element we can simply get 0th index or root node then assign last index to root node and then heapifyDown to place it its correct position.

Detail Description 





public class MyMaxHeap {

int [] maxHeapArray;
int size;

public MyMaxHeap(int size) {
this.maxHeapArray = new int[size+1];
this.size = 0;
}

void swap(int i, int j){
int temp = maxHeapArray[i];
maxHeapArray[i] = maxHeapArray[j];
maxHeapArray[j] = temp;
}

void heapifyDown(int index){
int largest = index;
int leftIndex = 2 * index;
int rightIndex = (2 * index) + 1;

if(leftIndex<maxHeapArray.length &&maxHeapArray[leftIndex]>maxHeapArray[largest])
            largest = leftIndex;
if(rightIndex< maxHeapArray.length && maxHeapArray[rightIndex]>maxHeapArray[largest])
         largest = rightIndex;
if(largest != index){
swap(largest, index);
heapifyDown(largest);
}
}

void heapifyUp(int index){
//sSystem.out.println(index+" ");
while(maxHeapArray[index]>maxHeapArray[index/2]){
swap(index, index/2);
index = index/2;
}
}

void push(int num){
maxHeapArray[size] = num;
heapifyUp(size);
size++;
if(size == maxHeapArray.length-1){
maxHeapArray = Arrays.copyOf(maxHeapArray, size*2);
}
}

int pop(){
if(size == 0)return -1;
int head = maxHeapArray[0];
maxHeapArray[0] = maxHeapArray[size];
heapifyDown(0);
size--;
return head;
}

void print(){
System.out.println(Arrays.toString(maxHeapArray));
}

int peek(){
return maxHeapArray[0];
}
public static void main(String[] args) {

MyMaxHeap m =new MyMaxHeap(6);
m.push(3);
m.push(5);
m.push(7);
m.push(12);
m.push(17);
m.push(32);
m.push(10);
m.push(71);
m.push(11);
m.push(14);
m.push(4);
m.push(15);
m.push(115);

m.print();
System.out.println(m.pop());
System.out.println(m.pop());
System.out.println(m.pop());
System.out.println(m.pop());
m.print();
System.out.println(m.peek());
m.print();
}
}







Post a Comment

Previous Post Next Post