Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void heapify(int a[], int n, int i)
  5. {
  6. int largest = i;
  7. int l = 2*i + 1;
  8. int r = 2*i + 2;
  9.  
  10. // If left child is larger than root
  11. if(l < n && a[l] > a[largest])
  12. largest = l;
  13. if(r < n && a[r] > a[largest])
  14. largest = r;
  15.  
  16. if(largest != i)
  17. {
  18. swap(a[i], a[largest]);
  19. heapify(a, n,largest);
  20. }
  21. }
  22.  
  23. void heapSort(int ar[], int n)
  24. {
  25. for(int i = n/2 - 1; i >= 0; i--){
  26. heapify(ar, n,i);
  27. }
  28.  
  29. for(int i = n - 1; i >= 0; i--){
  30. swap(ar[0], ar[i]);
  31. heapify(ar,i,0);
  32. }
  33. }
  34.  
  35. void print(int a[], int n)
  36. {
  37. for(int i = 0 ; i < n; i++){
  38. cout << a[i] << " ";
  39. }
  40. cout << endl;
  41. }
  42.  
  43. int main()
  44. {
  45. int ar[] = {12, 11, 13, 5, 6, 7};
  46. int n = sizeof(ar)/sizeof(ar[0]);
  47.  
  48. heapSort(ar,n);
  49. print(ar,n);
  50. return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement