| 8 | import java.util.NoSuchElementException; |
| 9 | |
| 10 | public class Heap |
| 11 | { |
| 12 | private int[] a; |
| 13 | private int n; |
| 14 | |
| 15 | public Heap() |
| 16 | { |
| 17 | a=new int[10]; |
| 18 | n=0; |
| 19 | a[0]=99999; |
| 20 | } |
| 21 | public Heap(int maxSize) |
| 22 | { |
| 23 | a=new int[maxSize]; |
| 24 | n=0; |
| 25 | a[0]=99999; |
| 26 | } |
| 27 | public void insert(int value) |
| 28 | { |
| 29 | n++; |
| 30 | a[n]=value; |
| 31 | restoreUp(n); |
| 32 | } |
| 33 | |
| 34 | private void restoreUp(int i) |
| 35 | { |
| 36 | int k=a[i]; |
| 37 | int iparent=i/2; |
| 38 | |
| 39 | while(a[iparent]<k) /* No sentinel : while(iparent>=1 && a[iparent]<k) */ |
| 40 | { |
| 41 | a[i]=a[iparent]; |
| 42 | i=iparent; |
| 43 | iparent=i/2; |
| 44 | } |
| 45 | a[i]=k; |
| 46 | } |
| 47 | |
| 48 | public int deleteRoot() |
| 49 | { |
| 50 | if(n==0) |
| 51 | throw new NoSuchElementException("Heap is Empty"); |
| 52 | |
| 53 | int maxValue=a[1]; |
| 54 | a[1]=a[n]; |
| 55 | n--; |
| 56 | restoreDown(1); |
| 57 | return maxValue; |
| 58 | } |
| 59 | |
| 60 | private void restoreDown(int i) |
| 61 | { |
| 62 | int k=a[i]; |
| 63 | int lchild=2*i, rchild=lchild+1; |
| 64 | |
| 65 | while(rchild<=n) |
| 66 | { |
| 67 | if( k>=a[lchild] && k>=a[rchild] ) |
nothing calls this directly
no outgoing calls
no test coverage detected