思路很简单 实现两个排序 然后比较即可 注意,题目里的“一轮”排序 在merge中是指merge的size变为原来的两倍;还有临时数组开大一点,不然最后几个会有段错误
//PAT-1-1035
#include <iostream>
#include <algorithm>
#include <string>
#include <math.h>
using namespace std;
int f_insert=0;
int f_merge=0;
int f=0;
int s1[1000]={0};
int result[1000]={0};
int temarray[1000]={0};
int comp(int s0[],int s1[],int n){
for (int i=0; i<n; i++) {
if (s0[i]!=s1[i]) {
return 0;
}
}
return 1;
}
void insertion_sort(int s[],int n){
int temp,i,j;
for ( i=1; i<n; i++) {
temp=s[i];
for ( j=i; j>0&&s[j-1]>temp; j--) {
s[j]=s[j-1];
}
s[j]=temp;
if (f_insert==1&&!comp(s, s1, n)&&f==0) {
f=1;
for (int i=0;i<n; i++ ) {
result[i]=s[i];
}
//return;
}
if( comp(s, s1, n)) {
f_insert=1;
}
}
}
void Merge(int s[],int temarray[],int left_begin,int right_begin,int right_end){
int left_end,num,pos;
left_end = right_begin-1;
pos = left_begin;
num = right_end-left_begin+1;
while (left_begin<=left_end && right_begin<=right_end) {
if (s[left_begin]<s[right_begin]) {
temarray[pos++]=s[left_begin++];
}else temarray[pos++]=s[right_begin++];
}
while (left_begin<=left_end) {
temarray[pos++]=s[left_begin++];
}
while (right_begin<=right_end) {
temarray[pos++]=s[right_begin++];
}
for (int i=0; i<num; i++,right_end--) {
s[right_end]=temarray[right_end];
}
}
void Msort_iter(int s[],int temarray[],int left,int right,int n){
for (int i=1; i<n; i*=2) {
for (int j=0; j<n; j+=i*2) {
Merge(s, temarray, j, j+i,j+2*i-1<n-1?j+2*i-1:n-1);
if (comp(s, s1, n)==1) {
f_merge=1;
}
}
if (f_merge==1&&comp(s, s1, n)==0&&f==0) {
f=1;
for (int i=0;i<n; i++ ) {
result[i] = s[i];
}
//return;
}
}
}
void Msort(int s[],int temarray[],int left,int right,int n){
int pivot;
if (left<right) {
pivot = (left+right)/2;
Msort(s, temarray, left, pivot,n);
Msort(s, temarray, pivot+1, right,n);
Merge(s,temarray,left,pivot+1,right);
if (1) {
for (int i=0;i<n; i++ ) {
cout<<s[i]<<" ";
}
cout<<endl;
}
}
}
void merge_sort(int s[],int n){
//temarray = new int(n);
//if (temarray!=nullptr) {
Msort_iter(s,temarray,0,n-1,n);
//delete [] temarray;
//}else cout<<"坏了,内存不够啦!";
}
int main(){
int n;
int s0[1000]={0};
int s2[1000]={0};
cin>>n;
for (int i=0; i<n; i++) {
cin>>s0[i];
s2[i]=s0[i];
}
for (int i=0; i<n; i++) {
cin>>s1[i];
}
insertion_sort(s0, n);
merge_sort(s2, n);
if (f_insert) {
cout<<"Insertion Sort"<<endl;
for (int i=0;i<n-1; i++ ) {
cout<<result[i]<<" ";
}
cout<<result[n-1];
return 0;
}
if (f_merge) {
cout<<"Merge Sort"<<endl;
for (int i=0;i<n-1; i++ ) {
cout<<result[i]<<" ";
}
cout<<result[n-1];
}
return 0;
}