Adrita

task 3( ds lab 5) 3rd sem

Feb 17th, 2020
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int heap_size;
  5.  
  6. int left(int i)
  7. {
  8. return 2*i;
  9. }
  10. int right(int i)
  11. {
  12. return 2*i+1;
  13. }
  14. int parent(int i)
  15. {
  16. return i/2;
  17. }
  18. void min_heapify(int A[],int i)
  19. {
  20. int l,r,smallest;
  21. l=left(i);
  22. r=right(i);
  23.  
  24. if(l<=heap_size && A[l]<A[i])
  25. smallest=l;
  26. else
  27. smallest=i;
  28.  
  29. if(r<=heap_size && A[r]<A[smallest])
  30. smallest=r;
  31.  
  32. if(smallest!=i)
  33. {
  34. swap(A[i],A[smallest]);
  35. min_heapify(A,smallest);
  36. }
  37.  
  38. }
  39. void build_min_heap(int h[])
  40. {
  41. for(int i=heap_size/2; i>0; i--)
  42. min_heapify(h,i);
  43. }
  44. int heap_min(int h[])
  45. {
  46. return h[1];
  47. }
  48. int heap_extract_min(int h[])
  49. {
  50. int mn;
  51. if(heap_size<=0)
  52. cout<<"Underflow"<<endl;
  53. else
  54. {
  55. mn=h[1];
  56. h[1]=h[heap_size];
  57. heap_size--;
  58. min_heapify(h,1);
  59. return mn;
  60. }
  61. build_min_heap(h);
  62. }
  63. void heap_decrease_key(int h[],int i, int key)
  64. {
  65. if(h[i]<key)
  66. {
  67. cout<<"ERROR";
  68. return;
  69. }
  70. else
  71. {
  72. h[i]=key;
  73. while(i>1&&h[parent(i)]>h[i])
  74. {
  75. swap(h[i],h[parent(i)]);
  76. i=parent(i);
  77. }
  78.  
  79. }
  80. build_min_heap(h);
  81. }
  82. void display(int h[])
  83. {
  84. for(int i=1; i<=heap_size; i++)
  85. cout<<h[i]<<" ";
  86. }
  87.  
  88. int main()
  89. {
  90. int h[100];
  91. cin>>heap_size;
  92. for(int i=1; i<=heap_size; i++)
  93. {
  94. cin>>h[i];
  95. }
  96. build_min_heap(h);
  97. cout<<"MIN HEAP is"<<endl;
  98. display(h);
  99. heap_decrease_key(h,2,1);
  100. cout<<"\nHeap decreased key"<<endl;
  101. display(h);
  102. heap_extract_min(h);
  103. cout<<"\nMin extracted"<<endl;
  104. display(h);
  105. }
Advertisement
Add Comment
Please, Sign In to add comment