Friday, 25 September 2015

MIN HEAP USING JAVA


  • In Min heap, we have to add element such that parent has minimum value than it’s child value.
  • Here we represent Min heap as tree and we are going to implement it with static array in which zero index has no value. We add value in array starting from index one as show in figure.
  • Here we have same concept of queue that FIFO(first in – first out)
Functionality :-
  • Enqueue – Add element at last.
  • Dequeue – Delete from first position.
  • Peek – Display First Element 
Advantage of Min heap:- Sorting become more efficient.

Enqueue :-
  • Suppose if we want to add 1 in upper Min heap than we have to add 1 at index 11 (suppose index 11 is there.).But as we know Min heap means child has maximum value that it’s parent but here 1<3, which is not possible that we have to swap that two value. For that what can do that Number[i/2]<->Number[i], means as we can here we have index 11 if take 11/2=5(in integer) than you can directly jump at it’s parent value and exchange that value. After exchanging that two value you will again find that 1<2 that again you can change that value with upper logic like this we have to move untill we don’t find that Number[i/2]>Number[i].
Dequeue:-
  • As we know for dequeue, we have to remove element from root or from first position for that we have to move last element of array (here we have 1) at first position but still parent should have minimum value than child for that we have compare Number[i] with Number[2*i] and Number[2*i+1] because of you again go through upper image than you will that parent (Number[i]) has two child Number[2*i] and Number[2*i+1].So we have to compare that value and if you find and minimum value of child than parent that swap those two value.
Peek:-
  • In peek we have where first element of array or tree.
Algorithm Of Min heap



Download :- Min Heap

No comments:

Post a Comment