This is my implementation of MinHeap in Java.
public class MinHeap {
int[] heap;
int pos;
int size;
public MinHeap(){
this.size = 2;
heap = new int[size];
this.pos = 0;
}
private void minHeapify(int index){
int child = index;
int parent = child/2;
while(heap[parent] > heap[child] && parent > 0){
int temp = heap[parent];
heap[parent] = heap[child];
heap[child] = temp;
child = parent;
parent = child/2;
}
}
public void add(int item){
if(pos == heap.length) resize();
heap[pos++] = item;
minHeapify(pos-1);
}
public void delete(int item){
boolean found = false;
int start = 0;
for(int i = 0; i< heap.length; i++){
if(heap[i] == item){
found = true;
start = i;
break;
}
}
if(found == false) throw new IllegalStateException("Item doesn't exist.");
pos--;
for(int i= start; i< pos; i++){
heap[i]= heap[i+1];
}
for(int i=pos; i > 0; i--){
minHeapify(i);
}
}
public int min(){
return heap[1];
}
private void resize(){
size = size*2;
int[] curr = new int[size];
for(int i=0; i< heap.length; i++){
curr[i] = heap[i];
}
heap = curr;
}
}
Invite comments and suggestions to improve.