1035 插入与归并 (25 分)(c++)
根據維基百科的定義:
插入排序是迭代算法,逐一獲得輸入數據,逐步產生有序的輸出序列。每步迭代中,算法從輸入序列中取出一元素,將之插入有序序列中正確的位置。如此迭代直到全部元素有序。
歸并排序進行如下迭代操作:首先將原始序列看成 N 個只包含 1 個元素的有序子序列,然后每次迭代歸并兩個相鄰的有序子序列,直到最后只剩下 1 個有序的序列。
現給定原始序列和由某排序算法產生的中間序列,請你判斷該算法究竟是哪種排序算法?
輸入格式:
輸入在第一行給出正整數 N (≤100);隨后一行給出原始序列的 N 個整數;最后一行給出由某排序算法產生的中間序列。這里假設排序的目標序列是升序。數字間以空格分隔。
輸出格式:
首先在第 1 行中輸出Insertion Sort表示插入排序、或Merge Sort表示歸并排序;然后在第 2 行中輸出用該排序算法再迭代一輪的結果序列。題目保證每組測試的結果是唯一的。數字間以空格分隔,且行首尾不得有多余空格。
輸入樣例 1:
10 3 1 2 8 7 5 9 4 6 0 1 2 3 7 8 5 9 4 6 0結尾無空行
輸出樣例 1:
Insertion Sort 1 2 3 5 7 8 9 4 6 0結尾無空行
輸入樣例 2:
10 3 1 2 8 7 5 9 4 0 6 1 3 2 8 5 7 4 9 0 6結尾無空行
輸出樣例 2:
Merge Sort 1 2 3 8 4 5 7 9 0 6結尾無空行
#include<iostream> #pragma warning (disable:4996) #include <algorithm> #include <iostream> using namespace std; bool judge(int orgin[], int sorted[],int N);//數組不同返回1 int main() {int N;int orgin[100], sorted[100];scanf("%d", &N);for (int cnt = 0; cnt < N; cnt++) cin >> orgin[cnt];for (int cnt = 0; cnt < N; cnt++) cin >> sorted[cnt];int i, j;for (i = 0; i < N && sorted[i] <= sorted[i + 1]; i++);for (j = i + 1; j < N && sorted[j] == orgin[j]; j++);if (j == N) {cout << "Insertion Sort" << endl;sort(orgin, orgin + i + 2);}else {cout << "Merge Sort" << endl;int flag = 1, beishu = 1;while (flag) {flag = judge(orgin, sorted, N);for (int cnt = 0; cnt < N / beishu; cnt++) {sort(orgin + beishu * cnt, orgin + beishu * (cnt + 1));}sort(orgin + N / beishu * beishu, orgin + N);beishu *= 2;}}for (int cnt = 0; cnt < N; cnt++)printf("%d%s", orgin[cnt], (cnt != N - 1) ? " " : "");return 0;} bool judge(int orgin[], int sorted[], int N) {int flag = 0;for (int cnt = 0; cnt < N; cnt++) {if (orgin[cnt] != sorted[cnt]) flag = 1;}return flag; }歸并循環中若cnt==N/k,是對一整個數組進行排列,但是其實有可能會有剩余下來的,比如說14,在被歸并為4數組 的時候,就會導致有兩個沒有相鄰給他歸并,那么我們就要單獨對他進行歸并,又因為防止越界訪問,所以我們循環設置成了cnt<N/k,對最后剩下來的那一部分單獨運算
注意:sort()中第二個參數是最后一個元素的后一個地址.
注意下,如果有浮點錯誤的話,應該是第一個找i那里出問題了,那里必須<=,我也不知為什么
總結
以上是生活随笔為你收集整理的1035 插入与归并 (25 分)(c++)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1034 有理数四则运算 (20 分)(
- 下一篇: 1036 跟奥巴马一起编程 (15 分)