数据结构01- 09-排序2 Insert or Merge
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #define MAXN 102 3 int n,a[MAXN],p[MAXN],A[MAXN]; 4 void read(); 5 int insertion_sort(); 6 void merge_sort(); 7 void merge_pass(int a[],int tmpa[],int n,int length); 8 void merge(int a[],int tmpa[],int l,int r,int rend); 9 void print(int a[]); 10 int test(int a[],int b[]); 11 void init(); 12 int main(){ 13 read(); 14 if(insertion_sort()==0) {init();merge_sort();} 15 return 0; 16 } 17 void init(){ 18 for(int i=0;i<n;i++){ 19 a[i] = A[i]; 20 } 21 } 22 void read(){ 23 scanf("%d",&n); 24 for(int i=0;i<n;i++) {scanf("%d",&a[i]); A[i] = a[i];} 25 for(int i=0;i<n;i++) scanf("%d",&p[i]); 26 } 27 void print(int a[]){ 28 for(int i=0;i<n;i++){ 29 printf("%d",a[i]); 30 if(i!=n-1) printf(" "); 31 } 32 printf("\n"); 33 } 34 int test(int a[],int b[]){ 35 for(int i=0;i<n;i++) 36 if(a[i]!=b[i]) return 0; 37 return 1; 38 } 39 int insertion_sort(){ 40 int i,j,flag=0,value; 41 for(i=1;i<n;i++){ 42 value = a[i]; 43 for(j=i;a[j-1]>value && j>0;j--) 44 a[j] = a[j-1]; 45 a[j] = value; 46 if(flag==1) 47 { 48 printf("Insertion Sort\n"); 49 print(a); 50 return 1; 51 } 52 flag = test(a,p); 53 } 54 return 0; 55 } 56 void merge_sort(){ 57 int length=1,flag=0; 58 int tmpa[MAXN]; 59 while(length<n){ 60 merge_pass(a,tmpa,n,length); 61 if(flag==1) {printf("Merge Sort\n");print(tmpa); return;} 62 flag = test(tmpa,p); 63 length *= 2; 64 merge_pass(tmpa,a,n,length); 65 if(flag==1) {printf("Merge Sort\n");print(a);return;} 66 flag = test(tmpa,p); 67 } 68 } 69 void merge_pass(int a[],int tmpa[],int n,int length){ 70 int i; 71 for( i=0;i<=n-2*length;i+=2*length){ 72 merge(a,tmpa,i,i+length,i+2*length-1); 73 } 74 if(i+length>=n){ 75 for(int j=i;j<n;j++) tmpa[j] = a[j]; 76 } 77 else{ 78 merge(a,tmpa,i,i+length,n-1); 79 } 80 } 81 void merge(int a[],int tmpa[],int l,int r,int rend){ 82 int tmpl = l; 83 int le = r-1; 84 while(l<=le&&r<=rend){ 85 if(a[l]>a[r]) {tmpa[tmpl++] = a[r]; r++;} 86 else if(a[l]<a[r]){tmpa[tmpl++] = a[l];l++;} 87 else {tmpa[tmpl++] = a[l]; tmpa[tmpl++] = a[r];l++;r++;} 88 } 89 while(l<=le){ 90 tmpa[tmpl++] = a[l]; 91 l++; 92 } 93 while(r<=rend){ 94 tmpa[tmpl++] = a[r]; 95 r++; 96 } 97 98 }