浙大pat | 浙大pat 牛客网甲级1061 Insert or Merge (25)判断是插入排序还是归并排序

According to Wikipedia:

Insertion sort iterates, consuming one input element each repetition, andgrowing a sorted output list. Each iteration,

insertion sort removes one element from the input data, finds the location itbelongs within the sorted list, and inserts

it there. It repeats until no input elements remain.

Merge sort works as follows: Divide the unsorted list into N sublists, each containing1 element (a list of 1 element is

considered sorted). Then repeatedly merge two adjacent sublists to produce newsorted sublists until there is only 1

sublist remaining.

Now given the initial sequence of integers, together with a sequence which is aresult of several iterations of some

sorting method, can you tell which sorting method we are using?

Each input file contains one test case. For each case, the firstline gives a positive integer N (<=100). Then in the next line, N integersare

given as the initial sequence. The last line contains the partially sortedsequence of the N numbers. It is assumed that the target

sequence is always ascending. All the numbers in a line are separated by a space.

For each test case, print in the first line either"Insertion Sort" or "Merge Sort" to indicate the methodused to obtain the partial result.

Then run this method for one more iteration and output in the second line theresulting sequence. It is guaranteed that the answer is

unique for each test case. All the numbers in a line must be separated by aspace, and there must be no extra space at the end of the

line.

10

3 1 2 8 7 5 9 4 6 0

1 2 3 7 8 5 9 4 6 0

Insertion Sort

1 2 3 5 7 8 9 4 6 0

#include <iostream>
#include <string>
#include<algorithm>
using namespace std;

int theOther;
int num;
int main()
{
int N;
cin >> N;
string whatSide;
int tmp;
for (int i = 0; i < N; i++)
{
cin >> theOther[i];
}
for (int i = 0; i < N; i++)
{
cin >> num[i];
}

for (int i = 1; i < N; i++)
{
if (num[i] < num[i - 1])
{
int j = i;
tmp = i;
for (; j < N; j++)
if (theOther[j] == num[j]) continue;
else break;

if (j == N) whatSide = "Insertion Sort";
else whatSide = "Merge Sort";
break;
}
}
if (whatSide == "Insertion Sort")
{
for (int i = tmp; i >= 0; i--)
{
if (num[i] < num[i - 1])
{
swap(num[i], num[i - 1]);
}
else
{
break;
}
}
}
else
{
int length = 2;
int start = 0;
int index = start+1;
for (; length < N * 2; length *= 2)
{
start = 0;
index = start + 1;
bool theFind = false;
while (1)
{
while (index < start + length&&index < N)
{
if (num[index] >= num[index - 1]) { index++; continue; }
else
{
theFind = true;
break;
}
}
if (theFind)
{
for(int i=start;i<N;i+=length)
sort(num + i, num +min(i+length,N));
goto allEnd;
}
if (index >= N) break;
start += length; index = start + 1;
}
}
allEnd:;
}
cout << whatSide << endl;
for (int i = 0; i < N; i++)
{
cout << num[i];
if (i != N - 1) cout << " ";
}
return 0;
} 