10-排序6 Sort with Swap(0, i) (25 分)

按照陈越姥姥讲的思想做的,但是由于归并排序用的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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值