1035 插入与归并 (25 分)

题目链接:1035 插入与归并 (25 分)

 

这道题目终于AC了!!!

刚开始选用了不可靠的判定排序类型的方法。我想通过输入的第二个数组的特征直接判定是插入排序还是归并排序。

但是通过这个方法测试点6总是过不了。上网看看其他人的操作,都是按照题目要求对原数组进行排序,排序过程中

如果数组匹配,则断定排序类型然后按照题目要求输出即可。于是我开始怀疑我的判定方法……经过严密分析(完全

是遐想的)发现我的判定方法有歧义。即在某种情况下,数列的两种排序方法可能造成相同的中间结果。直接利用题目

给定的中间结果判定是不可靠的。意识到这一点后,我重新开始编写。即利用sort模拟插入排序和归并排序,抓住匹配

的结果,并输出下一步的结果!

遇到的困难:

1、没有选定合适的,可靠的逻辑判定

2、基本排序方法不是很熟练理解。

 

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int a[102];
 5 int b[102];
 6 int temp[102];
 7  
 8 bool arrycmp(int c[],int n)
 9 {
10     for(int i=0;i<n;i++)
11     {
12         if(c[i]!=b[i])
13             return false;    //两个数组不相等 
14     } 
15     return true;    //两个数组相等 
16 } 
17 
18 void printarry(int a[],int n)
19 {
20     for(int i=0;i<n;i++)
21     {
22         cout<<a[i];
23         if(i!=n-1)
24             cout<<" ";
25     }    
26 }
27 bool InsertSort(int a[],int n)
28 {
29     int count=2;
30     for(;count<=n;count++)
31     {
32         sort(a,a+count);
33         if(arrycmp(a,n))    //两个数组相等
34         {
35             cout<<"Insertion Sort"<<endl;
36             sort(a,a+count+1);
37             printarry(a,n);
38             return true;    //匹配成功! 
39         }             
40     }
41     return false;
42 }
43 
44 void MergeInsert(int a[],int n)
45 {
46     int count=1;
47     int pos;
48     for(;count<=n;)
49     {
50         for(int i=0;i+count<=n;i+=count,pos=i)
51         {
52             sort(a+i,a+i+count);
53         }
54         if(pos<n)
55             sort(a+pos,a+n);
56         if(2*count>=n)
57             count=n;
58         else
59             count*=2;
60         if(arrycmp(a,n))    //如果匹配成功
61         {
62             cout<<"Merge Sort"<<endl;
63             for(int i=0;i+count<=n;i+=count,pos=i)
64                 sort(a+i,a+i+count);
65             if(pos<n)
66                 sort(a+pos,a+n);
67             printarry(a,n);
68             break;
69         } 
70     }
71 }
72 int main()
73 {
74     int n;
75     cin>>n;
76     for(int i=0;i<n;i++)
77     {
78         cin>>a[i];
79         temp[i]=a[i];
80     }
81     for(int i=0;i<n;i++)
82         cin>>b[i];
83     if(!InsertSort(a,n))
84         MergeInsert(temp,n);
85     return 0;    
86 }     

 

posted @ 2019-01-19 21:15  focusDing  阅读(726)  评论(0编辑  收藏  举报