这题略。。。恶心。。
他说归并排序依次是相邻有序两块合并,而一向打惯了递归???
#include <bits/stdc++.h> using namespace std; typedef long long LL; const int N=1e2+10; int b[N]; void Merge(int a[], int temp[], int Left, int Mid, int Right) { int i,tp=Left; int dis=Right-Left+1; int Leftend=Mid-1; while(Left<=Leftend&&Mid<=Right) if(a[Left]<a[Mid]) temp[tp++]=a[Left++]; else temp[tp++]=a[Mid++]; while(Left<=Leftend) temp[tp++]=a[Left++]; while(Mid<=Right) temp[tp++]=a[Mid++]; for(i=0;i<dis;i++,Right--) a[Right]=temp[Right]; } bool Check(int a[],int n) { for(int i=0;i < n;i++) if(a[i]!=b[i]) return false; return true; } bool InsertionSort(int a[],int n) { int temp,i,j; for(i=1;i<=n-1;i++) { temp=a[i]; for(j=i-1;j>=0;j--) { if(a[j]<temp) break; a[j+1]=a[j]; } a[j+1]=temp; if(Check(a,n)) { i++; temp=a[i]; for(j=i-1;j>=0;j--) { if(a[j]<temp) break; a[j+1]=a[j]; } a[j+1]=temp; puts("Insertion Sort"); for(int k=0;k<n;k++) { if(k) printf(" "); printf("%d",a[k]); } return true; } } return false; } bool MergeSort(int a[],int temp[],int n) { int dis=1,Left,Right,Mid; while(1) { Left=0; while(1) { Mid=Left+dis; if(Mid>=n) break; Right=Left+2*dis-1; if(Right>=n) { Right=n-1; Merge(a,temp,Left,Mid,Right); break; } else Merge(a,temp,Left,Mid,Right); Left=Right+1; if(Left>=n) break; } dis*=2; if(Check(a,n)) { Left=0; while(1) { Mid=Left+dis; if(Mid>=n) break; Right=Left+2*dis-1; if(Right>=n) { Right=n-1; Merge(a,temp,Left,Mid,Right); break; } else Merge(a,temp,Left,Mid,Right); Left=Right+1; if(Left>=n) break; } puts("Merge Sort"); for(int k=0;k<n;k++) { if(k) printf(" "); printf("%d",a[k]); } puts(""); return true; } } return false; } int main() { int c[N],a[N],temp[N],n; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&a[i]); c[i]=a[i]; } for(int i=0;i<n;i++) scanf("%d",&b[i]); if(InsertionSort(c,n)) return 0; if(MergeSort(a,temp,n)) return 0; }