zoukankan      html  css  js  c++  java
  • C++ PTA 1035 插入与归并 (25 分)

    https://pintia.cn/problem-sets/994805260223102976/problems/994805286714327040

    • equal(a,a+i,b)
    • 比较a,b两容器中长度为 i 的数据是否相等,返回bool值。包含在algorithm中

    若是插入排序,必定存在某个位置,在这个位置前,排序数组是有序的;位置后,原数组和排序后数组相等。

    否则就是归并排序。直接模拟归并排序的流程,判断在哪一步排序数组等于模拟归并数组,之后再进行一次归并即可。

     1 #include<iostream>
     2 #include<algorithm>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     int n,a[100], b[100], insertPos;
     8     bool isInsert = true;
     9     cin >> n;
    10     for(int i=0;i<n;i++)
    11         cin >> a[i];
    12     for(int i=0;i<n;i++)
    13         cin >> b[i];
    14     for(insertPos=1; insertPos<n; insertPos++)
    15         if(b[insertPos]<b[insertPos-1])
    16             break;
    17     for(int i=insertPos; i<n; i++)
    18         if(a[i] != b[i])
    19         {
    20             isInsert = false;
    21             break;
    22         }
    23     if(isInsert)
    24     {
    25         cout << "Insertion Sort" << endl;
    26         sort(a,a+insertPos+1);
    27     }
    28     else
    29     {
    30         cout << "Merge Sort" << endl;
    31         int temp = 2;
    32         while(!equal(a,a+n,b))
    33         {
    34             for(int i=0; i<n; i+=temp)
    35                 sort(a+i,a+min(i+temp, n));
    36             temp = temp*2;
    37         }
    38         for(int i=0; i<n; i+=temp)
    39                 sort(a+i,a+min(i+temp, n));
    40     }
    41     for(int i=0; i<n-1; i++)
    42         cout << a[i] << ' ';
    43     cout << a[n-1];
    44     return 0;
    45 }
  • 相关阅读:
    ActionBar认知
    CSS动画-多列
    CSS3动画效果
    GreenDao数据库框架
    Handler介绍
    AsyncTask介绍
    Android中IntentService的原理及使用
    English interview!
    第六章 结构
    结构体中定义函数指针
  • 原文地址:https://www.cnblogs.com/tornado549/p/11771015.html
Copyright © 2011-2022 走看看