Chinaunix首页 | 论坛 | 博客
  • 博客访问: 264229
  • 博文数量: 45
  • 博客积分: 930
  • 博客等级: 准尉
  • 技术积分: 553
  • 用 户 组: 普通用户
  • 注册时间: 2012-01-22 17:53
文章分类

全部博文(45)

文章存档

2013年(5)

2012年(40)

分类: C/C++

2012-12-11 15:54:12


点击(此处)折叠或打开

  1. #include <iostream>
  2. #define UPS
  3. using namespace std;


  4. void adjust(int list[],int root,int n)
  5. {
  6.     int child, rootkey;
  7.     int temp;
  8.     temp = list[root];
  9.     rootkey = list[root];
  10.     child = 2 * root;
  11.     while(child <= n)
  12.     {
  13.         if ((child < n) && (list[child] < list[child+1]))
  14.             child++;
  15.         if (rootkey > list[child])
  16.             break;
  17.         else{
  18.             list[child/2] = list[child];
  19.             child *= 2;
  20.         }
  21.     }
  22.     list[child/2] = temp;
  23. }

  24. void heapsort(int list[],int n)
  25. {
  26.     int i;
  27.     int temp;

  28.     for ( i = n/2; i > 0; i--)//建大堆
  29.         adjust(list,i,n);
  30.     for(i = n-1; i >0;i--)
  31.     {
  32. #ifdef UPS
  33.         temp = list[1];
  34.         list[1] = list[i+1];
  35.         list[i+1] = temp;
  36. #else
  37.         cout<<list[1]<<" ";
  38.         list[1] = list[i+1];
  39. #endif
  40.         adjust(list,1,i);
  41.     }
  42. #ifndef UPS
  43.     cout<<list[1]<<" ";
  44. #endif
  45. }

  46. int main()
  47. {
  48.     int great[8] = {0,13,15,90,45,32,24,37};
  49.     heapsort(great,7);
  50. #ifdef UPS
  51.     for (int i = 1; i< 8; i++)
  52.         cout<<great[i]<<" ";
  53. #endif
  54.     return 0;
  55. }
输出结果:


若注释#define UPS 则可以输出倒序结果。
阅读(1915) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~