scopolamine

Heap Sort

Apr 20th, 2011
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. /*
  2. Heapsort(A as array)
  3.     BuildHeap(A)
  4.     for i = n to 1
  5.         swap(A[1], A[i])
  6.         n = n - 1
  7.         Heapify(A, 1)
  8.  
  9. BuildHeap(A as array)
  10.     n = elements_in(A)
  11.     for i = floor(n/2) to 1
  12.         Heapify(A,i)
  13.  
  14. Heapify(A as array, i as int)
  15.     left = 2i
  16.     right = 2i+1
  17.  
  18.     if (left <= n) and (A[left] > A[i])
  19.         max = left
  20.     else
  21.         max = i
  22.  
  23.     if (right<=n) and (A[right] > A[max])
  24.         max = right
  25.  
  26.     if (max != i)
  27.         swap(A[i], A[max])
  28.         Heapify(A, max)
  29. [edit]
  30. */
  31. #include <iostream>
  32. #include <stdio.h>
  33. using namespace std;
  34.  
  35. void heapify(int *a, int root, int bottom)
  36. {
  37.     int done, max, temp;
  38.  
  39.     done = 0;
  40.     while ((root*2 <= bottom) && (!done))
  41.     {
  42.         if (root*2 == bottom)
  43.             max = root * 2;
  44.         else if (a[root * 2] > a[root * 2 + 1])
  45.             max = root * 2;
  46.         else
  47.             max = root * 2 + 1;
  48.  
  49.         if (a[root] < a[max])
  50.         {
  51.             temp = a[root];
  52.             a[root] = a[max];
  53.             a[max] = temp;
  54.             root = max;
  55.         }
  56.         else
  57.             done = 1;
  58.     }
  59. }
  60.  
  61. void heapsort(int *a, int size)
  62. {
  63.     int i, temp;
  64.  
  65.     for (i = (size / 2)-1; i >= 0; i--)
  66.         heapify(a, i, size - 1);
  67.  
  68.     for (i = size-1; i >= 1; i--)
  69.     {
  70.         temp = a[0];
  71.         a[0] = a[i];
  72.         a[i] = temp;
  73.         heapify(a, 0, i-1);
  74.     }
  75. }
  76.  
  77. int main()
  78. {
  79.     int a[10]={12,48,67,34,25,85,93,55,10,77};
  80.     for(int k=0; k<10; k++)
  81.     {
  82.     cout<< a[k] << " ";
  83.     }
  84.     cout << "\n\n";
  85.     heapsort(a, 10);
  86.     for(int k=0; k<10; k++)
  87.     {
  88.     cout<< a[k] << " " << endl;
  89.     }
  90.     system("pause");
  91. }
Advertisement
Add Comment
Please, Sign In to add comment