- #include <iostream>
- #define UPS
- using namespace std;
- void adjust(int list[],int root,int n)
- {
- int child, rootkey;
- int temp;
- temp = list[root];
- rootkey = list[root];
- child = 2 * root;
- while(child <= n)
- {
- if ((child < n) && (list[child] < list[child+1]))
- child++;
- if (rootkey > list[child])
- break;
- else{
- list[child/2] = list[child];
- child *= 2;
- }
- }
- list[child/2] = temp;
- }
- void heapsort(int list[],int n)
- {
- int i;
- int temp;
- for ( i = n/2; i > 0; i--)//建大堆
- adjust(list,i,n);
- for(i = n-1; i >0;i--)
- {
- #ifdef UPS
- temp = list[1];
- list[1] = list[i+1];
- list[i+1] = temp;
- #else
- cout<<list[1]<<" ";
- list[1] = list[i+1];
- #endif
- adjust(list,1,i);
- }
- #ifndef UPS
- cout<<list[1]<<" ";
- #endif
- }
- int main()
- {
- int great[8] = {0,13,15,90,45,32,24,37};
- heapsort(great,7);
- #ifdef UPS
- for (int i = 1; i< 8; i++)
- cout<<great[i]<<" ";
- #endif
- return 0;
- }
输出结果:
若注释#define UPS 则可以输出倒序结果。
阅读(1955) | 评论(0) | 转发(0) |