题目:https://www.patest.cn/contests/pat-a-practise/1098
1098. Insertion or Heap Sort (25)
照着学习了一遍精神的代码
1 #include2 #include 3 4 using namespace std; 5 #define MAXN 111 6 int origin[MAXN],tempOri[MAXN],changed[MAXN]; 7 int n; 8 bool isSame(int *A,int *B){ 9 for(int i=0;i<=n;i++)10 if(A[i]!=B[i])11 return false;12 return true;13 }14 15 bool showArray(int *A){16 for(int i=1;i<=n;i++){17 printf("%d",A[i]);18 if(i tempOri[j]){40 j++;41 }42 if(tempOri[j]>tempOri[i]){43 swap(tempOri[j],tempOri[i]);44 i=j;45 j=i*2;46 }else{47 break;48 }49 }50 }51 52 void heapSort(){53 bool flag=false;54 for(int i=n/2;i>=1;i--){55 downAdjust(i,n);56 }57 for(int i=n;i>1;i--){58 if(i!=n&&isSame(tempOri,changed)){59 flag=true;60 }61 swap(tempOri[i],tempOri[1]);62 downAdjust(1,i-1);63 if(flag){64 showArray(tempOri);65 return;66 }67 }68 }69 70 int main()71 {72 scanf("%d",&n);73 for(int i=1;i<=n;i++){74 scanf("%d",&origin[i]);75 tempOri[i]=origin[i];76 }77 for(int i=1;i<=n;i++){78 scanf("%d",&changed[i]);79 }80 if(insertSort()){81 printf("Insertion Sort\n");82 showArray(tempOri);83 }else{84 printf("Heap Sort\n");85 for(int i=1;i<=n;i++){86 tempOri[i]=origin[i];87 }88 heapSort();89 }90 return 0;91 }