這個算法有點難感受
嗚嗚嗚o(╥﹏╥)o
這裏有原理ios
//算法8.11 歸併排序 #include <iostream> using namespace std; #define MAXSIZE 20 //順序表的最大長度 typedef struct { int key; char *otherinfo; }RedType; typedef struct { RedType *r; int length; }SqList; void Create_Sq(SqList &L) { int i,n; cout<<"請輸入數據個數,不超過"<<MAXSIZE<<"個。"<<endl; cin>>n; //輸入個數 cout<<"請輸入待排序的數據:\n"; while(n>MAXSIZE) { cout<<"個數超過上限,不能超過"<<MAXSIZE<<",請從新輸入"<<endl; cin>>n; } for(i=1;i<=n;i++) { cin>>L.r[i].key; L.length++; } } //用算法8.10 相鄰兩個有序子序列的歸併 void Merge(RedType R[],RedType T[],int low,int mid,int high) { //將有序表R[low..mid]和R[mid+1..high]歸併爲有序表T[low..high] int i,j,k; i=low; j=mid+1;k=low; while(i<=mid&&j<=high) { //將R中記錄由小到大地併入T中 if(R[i].key<=R[j].key) T[k++]=R[i++]; else T[k++]=R[j++]; } while(i<=mid) //將剩餘的R[low..mid]複製到T中 T[k++]=R[i++]; while(j<=high) //將剩餘的R[j.high]複製到T中 T[k++]=R[j++]; }//Merge void MSort(RedType R[],RedType T[],int low,int high) { //R[low..high]歸併排序後放入T[low..high]中 int mid; RedType *S=new RedType[MAXSIZE]; if(low==high) T[low]=R[low]; else { mid=(low+high)/2; //將當前序列一分爲二,求出分裂點mid MSort(R,S,low,mid); //對子序列R[low..mid] 遞歸歸併排序,結果放入S[low..mid] MSort(R,S,mid+1,high); //對子序列R[mid+1..high] 遞歸歸併排序,結果放入S[mid+1..high] Merge(S,T,low,mid,high); //將S[low..mid]和S [mid+1..high]歸併到T[low..high] }//else }// MSort void MergeSort(SqList &L) { //對順序表L作歸併排序 MSort(L.r,L.r,1,L.length); }//MergeSort void show(SqList L) { int i; for(i=1;i<=L.length;i++) cout<<L.r[i].key<<endl; } void main() { SqList R; R.r=new RedType[MAXSIZE+1]; R.length=0; Create_Sq(R); MergeSort(R); cout<<"排序後的結果爲:"<<endl; show(R); }