按照陈越姥姥讲的思想做的,但是由于归并排序用的sort函数,也没提高多少运行时间。
1.插入排序:前面有序,后面没变化
归并排序:分段有序
先通过这个特征判断是否为插入排序
2.如果是插入排序,则在插入排序的基础上再执行
3.如果相反,则执行归并排序
注意:1)数组涉及到i+1的时候,边界条件为i<N-1;
2)插入排序的下标为0-N-1,则待排序的元素可以最小放到下标为0的地方
3)
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int maxn = 101;
int N;
int beforeSort[maxn], afterSort[maxn];
int temp;//临时存储跳出的地点
bool JudgeInsertSort() {//判断是否为插入排序
for (int i = 0; i < N - 1; i++) {
if (afterSort[i] <= afterSort[i + 1])continue;
else {
temp = i;
break;
}
}
for (int j = temp + 1; j < N; j++) {
if (afterSort[j] != beforeSort[j]) {
return false;
}
}
return true;
}
void InsertSort() {
int tmp = afterSort[temp + 1];
int j = temp + 1;
while (j>0&&tmp<afterSort[j-1])
{
afterSort[j] = afterSort[j - 1];
j--;
}
afterSort[j] = tmp;
for (int i = 0; i < N; i++)
{
if(i==0)cout<< afterSort[i];
else {
cout<<" "<< afterSort[i];
}
}
}
int stepNum() {
int step = 2;
for (; step / 2 < N; step *= 2) {
for (int i = step - 1; i < N-1; i += step * 2) {
if (afterSort[i] > afterSort[i + 1]) {
return step;
}
}
}
return step/2;
}
void MergeSort() {
int step = stepNum();
//cout << step;
for (int i = 0; i < N; i += step *2) {
sort(afterSort + i, afterSort + min(i + step *2, N));
}
for (int i = 0; i < N; i++)
{
if (i == 0)cout << afterSort[i];
else {
cout << " " << afterSort[i];
}
}
}
int main() {
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> beforeSort[i];
}
for (int i = 0; i < N; i++)
{
cin >> afterSort[i];
}
if (JudgeInsertSort()==true)
{
cout << "Insertion Sort" << endl;
InsertSort();
}
else {
cout << "Merge Sort" << endl;
MergeSort();
}
system("pause");
return 0;
}