1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #include<iostream> using namespace std; #define MAXSIZE 100 #define Status bool #define KeyType int #define InfoType int #define LT(x, y) (x<y?1:0) typedef struct{ KeyType key; InfoType info; }ElemType; typedef struct{ ElemType r[MAXSIZE+1]; int length; }SqList; typedef SqList HeapType;
Status HeapAdjust(HeapType &H, int s, int m); Status HeapSort(HeapType &H); int main() { HeapType H; cout << "Input the length of the sequence:\n"; cin >> H.length; for(int i=1;i<=H.length;i++) cin >> H.r[i].key; HeapSort(H); cout << "After Heap Sorting output the sequence:\n"; for(int i=1;i<=H.length;i++) cout << H.r[i].key << " "; return 0; } Status HeapAdjust(HeapType &H, int s, int m) { ElemType rc = H.r[s]; for(int j=2*s;j<=m;j*=2){ if(j<m && LT(H.r[j].key, H.r[j+1].key)) j++; if(!LT(rc.key, H.r[j].key)) break; H.r[s] = H.r[j]; s = j; } H.r[s] = rc; return true; }
Status HeapSort(HeapType &H) { for(int i=H.length/2;i>0;--i) HeapAdjust(H, i, H.length);
for(int i=H.length;i>1;i--){ ElemType temp = H.r[1]; H.r[1] = H.r[i]; H.r[i] = temp; HeapAdjust(H, 1, i-1); } return true; }
|