rootUser

Heap Sort (OWN)

Jul 9th, 2016
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdlib>
  3. using namespace std;
  4.  
  5. int arraySize;
  6. int A[100];
  7.  
  8. void input();
  9. void Max_Heapify(int,int);
  10. void Build_Max_Heap(int);
  11. void HeapSort(int);
  12. void output();
  13.  
  14. int main()
  15. {
  16.     input();
  17.     HeapSort(arraySize);
  18.     output();
  19.     return 0;
  20. }
  21. void input()
  22. {
  23.     int i;
  24.     cout<<"How many numbers : ";
  25.     cin>>arraySize;
  26.     for(i=1;i<=arraySize;i++)
  27.     {
  28.         A[i]=rand()%100;
  29.     }
  30.     A[0]=INT_MIN;
  31.     cout<<"Input : "<<endl;
  32.     for(i=1;i<=arraySize;i++)
  33.     {
  34.         cout<<A[i]<<" ";
  35.     }
  36.     cout<<endl;
  37. }
  38. void output()
  39. {
  40.     cout<<"Output : "<<endl;
  41.     int i;
  42.     for(i=1;i<=arraySize;i++)
  43.     {
  44.         cout<<A[i]<<" ";
  45.     }
  46.     cout<<endl;
  47. }
  48. void Max_Heapify(int i, int n)
  49. {
  50.     int l, r, largest = 1;
  51.  
  52.     l = 2*i;//Left(i);
  53.     r = 2*i+1;//Right(i);
  54.  
  55.     if((l<= n) && (A[l]> A[i]) )
  56.     {
  57.         largest = l;
  58.     }
  59.     else
  60.     {
  61.         largest = i;
  62.     }
  63.     if((r<=n) && (A[r] > A[largest]))
  64.     {
  65.         largest = r;
  66.     }
  67.     if(largest != i)
  68.     {
  69.         int temp = A[i];
  70.         A[i] = A[largest];
  71.         A[largest] = temp;
  72.         Max_Heapify(largest, n);
  73.     }
  74. }
  75. void Build_Max_Heap(int n)
  76. {
  77.     int i;
  78.     for (i = n/2; i>0; i--)
  79.     {
  80.         Max_Heapify(i, n);
  81.     }
  82. }
  83. void HeapSort(int n)
  84. {
  85.     Build_Max_Heap(n);
  86.     int i;
  87.     for (i = n; i>=2; i-- )
  88.     {
  89.         int temp = A[1];
  90.         A[1] = A[i];
  91.         A[i] = temp;
  92.  
  93.         Max_Heapify(1, i-1);
  94.     }
  95. }
Add Comment
Please, Sign In to add comment