堆排序
#include <iostream> using namespace std; int a[1005]; bool com1(int a,int b) { return a > b; } bool com2(int a,int b) { return a < b; } void adjust(int a[],int root,int length,bool com(int x,int y)) { int tem = a[root]; int child = 2*root; while (child <= length) { if (child<length && com(a[child],a[child+1])) child++; if (com(a[child],tem)) break; else{ a[root] = a[child]; root = child; child*=2; } } a[root] = tem; } void heapsort(int a[],int n,bool com(int x,int y)) { for (int i = n/2 ;i>=1; i--) adjust(a,i,n,com); for (int i = n-1; i>=1 ; i--) { swap(a[1],a[i+1]); adjust(a,1,i,com); } } void print(int a[],int n) { for (int i = 1; i<=n;i++) cout <<a[i]<<" "; cout <<endl; } int main() { int n; cin >> n; for (int i = 1; i<=n;i++) { cin >> a[i]; } heapsort(a,n,com1); print(a,n); heapsort(a,n,com2); print(a,n); }