Source:
Description:
According to Wikipedia:
Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs 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 containing 1 element (a list of 1 element is considered sorted). Then repeatedly merge two adjacent sublists to produce new sorted sublists until there is only 1 sublist remaining.
Now given the initial sequence of integers, together with a sequence which is a result of several iterations of some sorting method, can you tell which sorting method we are using?
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤). Then in the next line, N integers are given as the initial sequence. The last line contains the partially sorted sequence 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.
Output Specification:
For each test case, print in the first line either "Insertion Sort" or "Merge Sort" to indicate the method used to obtain the partial result. Then run this method for one more iteration and output in the second line the resuling sequence. It is guaranteed that the answer is unique for each test case. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.
Sample Input 1:
10 3 1 2 8 7 5 9 4 6 0 1 2 3 7 8 5 9 4 6 0
Sample Output 1:
Insertion Sort 1 2 3 5 7 8 9 4 6 0
Sample Input 2:
10 3 1 2 8 7 5 9 4 0 6 1 3 2 8 5 7 4 9 0 6
Sample Output 2:
Merge Sort 1 2 3 8 4 5 7 9 0 6
Keys:
- 插入排序和归并排序
Attention:
- 见注释
Code:
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 const int M=1e3; 5 6 int main() 7 { 8 #ifdef ONLINE_JUDGE 9 #else 10 freopen("Test.txt", "r", stdin); 11 #endif // ONLINE_JUDGE 12 13 int n,origin[M],sorted[M]; 14 scanf("%d", &n); 15 for(int i=0; i<n; i++) 16 scanf("%d", &origin[i]); 17 for(int i=0; i<n; i++) 18 scanf("%d", &sorted[i]); 19 int pos=1; 20 while(pos<n && sorted[pos-1]<=sorted[pos]) //可以取等 21 pos++; 22 int pt=pos; 23 while(pos<n && sorted[pos]==origin[pos]) 24 pos++; 25 if(pos == n) 26 { 27 printf("Insertion Sort\n"); 28 while(pt>0 && sorted[pt-1]>sorted[pt]) 29 { 30 swap(sorted[pt-1],sorted[pt]); 31 pt--; 32 } 33 } 34 else 35 { 36 printf("Merge Sort\n"); 37 pos=1;pt=1; 38 while(pt) 39 { 40 pos *= 2; 41 for(int i=0; i<n; i+=pos) 42 { 43 for(int j=i+1; j<min(n,i+pos); j++) 44 if(sorted[j-1]>sorted[j]) 45 pt=0; 46 } 47 } 48 for(int i=0; i<n; i+=pos) 49 sort(sorted+i,sorted+min(i+pos,n)); 50 } 51 for(int i=0; i<n; i++) 52 printf("%d%c", sorted[i], i==n-1?‘\n‘:‘ ‘); 53 54 return 0; 55 }
原文地址:https://www.cnblogs.com/blue-lin/p/11408491.html