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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| #include<iostream> using namespace std; #define Status bool #define Max_num 100 #define LT(x,y) (x<y?1:0)
typedef struct{ int key; }RcdType; typedef struct{ RcdType r[Max_num]; int length; }SqList;
Status NonCurMerge(SqList &L); Status MergeSort(RcdType *SR, RcdType *TR, int i, int m, int n);
Status CurMerge(SqList &L); Status MSort(RcdType *SR, RcdType *TR, int s, int t); int main() { SqList L1, L2; cout << "Input the length of sequence: "; cin >> L1.length; cout << "Input the elements of the sequence:\n"; for(int i=1;i<=L1.length;i++) cin >> L1.r[i].key; L2 = L1; NonCurMerge(L1); cout << "Output the sequence with NonCurrSortAlgorithm:\n"; for(int i=1;i<=L1.length;i++) cout << L1.r[i].key << " "; cout << endl; CurMerge(L2); cout << "Output the sequence with CurrSortAlgorithm:\n"; for(int i=1;i<=L2.length;i++) cout << L2.r[i].key << " "; cout << endl; return 0; } Status NonCurMerge(SqList &L) { int delta = 1, n = L.length; SqList T;T.length = n; while(delta < n){ for(int i=1;i<=n;i+=2*delta){ if(i+2*delta>n) MergeSort(L.r,T.r,i,i+delta-1,n); else MergeSort(L.r,T.r,i,i+delta-1,i+2*delta-1); } L = T; delta *= 2; } return true; } Status MergeSort(RcdType *SR, RcdType *TR, int i, int m, int n) { int j = m+1, k = i; while(i<=m&&j<=n){ if(LT(SR[i].key, SR[j].key)) TR[k++] = SR[i++]; else TR[k++] = SR[j++]; } while(i<=m) TR[k++] = SR[i++]; while(j<=n) TR[k++] = TR[j++]; return true; }
Status CurMerge(SqList &L) { MSort(L.r, L.r, 1, L.length); return true; } Status MSort(RcdType *SR, RcdType *TR, int s, int t) { RcdType TRtemp[Max_num]; if(s==t) TR[s] = SR[s]; else{ int m = (s + t)/2; MSort(SR, TRtemp, s, m); MSort(SR, TRtemp, m+1, t); MergeSort(TRtemp, TR, s, m, t); } return true; }
|