aryobarzan

heapsort using max-heap

May 25th, 2011
331
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. /*
  2.  * This is a simple max_heap
  3.  * function names are those used in CLRS
  4.  */
  5. #include <cstdio>
  6. #include <algorithm>
  7. #include <vector>
  8. using namespace std;
  9.  
  10. //these functions are inline to avoid function-call overload, could have used macros as well
  11. inline int left(int x)
  12. {
  13.   return x*2;
  14. }
  15. inline int right(int x)
  16. {
  17.   return x*2+1;
  18. }
  19. inline int parent(int x)
  20. {
  21.   return x/2;
  22. }
  23.  
  24. void max_heapify(vector<int> &array,int root,int heap_size)
  25. {
  26.   int maxi=root;
  27.   if(left(root)<=heap_size and array[left(root)]>array[maxi])
  28.     maxi=left(root);
  29.   if(right(root)<=heap_size and array[right(root)]>array[maxi])
  30.     maxi=right(root);
  31.   if(maxi==root)
  32.     return;
  33.   swap(array[maxi],array[root]);
  34.   max_heapify(array,maxi,heap_size);
  35. }
  36.  
  37. void make_max_heap(vector<int> &array)
  38. {
  39.   int heap_size=array.size()-1;
  40.   for(int i=heap_size/2+1;i>=1;--i)
  41.     max_heapify(array,i,heap_size);
  42. }
  43.  
  44. void heap_sort(vector<int> &array)
  45. {
  46.   make_max_heap(array);
  47.   int heap_size=array.size()-1;
  48.   while(heap_size)
  49.     {
  50.       swap(array[1],array[heap_size]);
  51.       heap_size--;
  52.       max_heapify(array,1,heap_size);
  53.     }
  54. }
  55.  
  56. int main()
  57. {
  58.   int n;
  59.   scanf("%d",&n);
  60.   vector<int> x;
  61.   x.push_back(-1);
  62.   x.resize(n+1,0);
  63.   for(int i=0;i<n;++i)
  64.     scanf("%d",&x[i+1]);
  65.   heap_sort(x);
  66.   for(int i=1;i<x.size();++i)
  67.     printf("%d ",x[i]);
  68.   printf("\n");
  69.   return -0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment