Advertisement
Adrita

task 2( ds lab 5) 3rd sem

Feb 17th, 2020
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 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 max_heapify(int A[],int i)
  19. {
  20. int l,r,largest;
  21. l=left(i);
  22. r=right(i);
  23.  
  24. if(l<=heap_size && A[l]>A[i])
  25. largest=l;
  26. else
  27. largest=i;
  28.  
  29. if(r<=heap_size && A[r]>A[largest])
  30. largest=r;
  31.  
  32. if(largest!=i)
  33. {
  34. swap(A[i],A[largest]);
  35. max_heapify(A,largest);
  36. }
  37.  
  38. }
  39. void build_max_heap(int A[],int len)
  40. {
  41. for(int i=len/2;i>0;i--)
  42. max_heapify(A,i);
  43. }
  44. void heap_sort(int A[],int length)
  45. {
  46. int len=length;
  47. build_max_heap(A,len);
  48. for(int i=length;i>1;i--)
  49. {
  50. swap(A[1],A[i]);
  51. heap_size--;
  52. max_heapify(A,1);
  53. }
  54. }
  55. int main()
  56. {
  57. cout<<"Heap Size:";
  58. cin>>heap_size;
  59. int A[heap_size+1];
  60. cout<<"UNSORTED INPUT"<<endl;
  61. for(int i=1;i<heap_size+1;i++)
  62. {
  63. cin>>A[i];
  64. }
  65. int length=sizeof(A)/sizeof(int)-1;
  66. cout<<"SORTED: ";
  67. heap_sort(A,length);
  68. for(int i=1;i<length+1;i++)
  69. {
  70. cout<<A[i]<<" ";
  71. }
  72. return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement