数据结构01- 09-排序3 Insertion or Heap Sort
#include<stdio.h> #define MAXN 102 int A[MAXN],a[MAXN],p[MAXN],n; void read(); void init(int a[]); int test(int a[],int b[]); int insertion_sort(int a[]); void heap_sort(int a[]); void print(int a[]); int main(){ read(); init(a); if(insertion_sort(a)==0) {init(a);heap_sort(a);} scanf("%d",&n); return 0; } void read(){ scanf("%d",&n); for(int i=0;i<n;i++)scanf("%d",&A[i]); for(int i=0;i<n;i++)scanf("%d",&p[i]); } void init(int a[]){ for(int i=0;i<n;i++) a[i] = A[i]; } int test(int a[],int b[]){ for(int i=0;i<n;i++) if(a[i]!=b[i]) return 0; return 1; } int insertion_sort(int a[]){ int value,i,j,flag=0; for(i=1;i<n;i++){ value = a[i]; for( j=i;a[j-1]>value&&j>0;j--) a[j] = a[j-1]; a[j] = value; if(flag==1) {printf("Insertion Sort\n");print(a);return 1;} flag = test(a,p); } return 0; } void print(int a[]){ for(int i=0;i<n;i++){ printf("%d",a[i]); if(i!=n-1) printf(" "); } printf("\n"); } void heap_sort(int a[]){ int j,value,flag=0,f; //justify heap for(int i=(n-3)/2+1;i>=0;i--){ f = i; j = i*2+1; while(j<n){ if((j+1)<n) if(a[j]<a[j+1]) j++; if(a[f]<a[j]){value = a[f]; a[f]=a[j];a[j] = value;f = j;j = f*2+1;} else break; } } //sort for(int count=n-1;count>=0;count--){ value = a[0]; a[0] = a[count]; a[count] = value; //justify f = 0; j = f*2+1; while(j<count){ if((j+1)<count) if(a[j]<a[j+1]) j++; if(a[j]>a[f]) { value = a[f]; a[f] = a[j]; a[j] = value; f = j; j = f*2+1; } else break; } //output if(flag==1){ printf("Heap Sort\n"); print(a); return; } flag = test(a,p); } }