算法(第4版) C++ 插入排序的优化

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法(第4版) C++ 插入排序的优化相关的知识,希望对你有一定的参考价值。

#include <iostream>
using namespace std;

void InsertSort_1(int *a, int n)
{
	for (int i = 1;i<n;i++)
		for (int j = i; j > 0 && a[j] < a[j - 1]; j--)
		{
			int t = a[j];
			a[j] = a[j - 1];
			a[j - 1] = t;
		}
}


void InsertSort_2(int *a, int n)
{
	for (int i = 1; i < n; i++)
	{
		int j;
		for (j = i - 1; j >= 0 && a[j] > a[i]; j--)
			a[j + 1] = a[j];
		a[j + 1] = a[i];
	}
}

int main()
{
	int a[] = { 213,534,13,311,532,421,3,124,123,12312,31 };
	InsertSort_1(a, 11);
	for (int i = 0; i < 11; i++) cout << a[i] << " ";
	cout << endl;
	int b[] = { 13,234,12,3,523,4,213,124,12,312,3,1241,2 };
	InsertSort_2(b, 12);
	for (int i = 0; i < 12; i++) cout << b[i] << " ";
	cout << endl;
	return 0;
}

测试结果:
在这里插入图片描述

分析:
InsertSort_1:
对于1到n-1之间的每一个i,将a[i]与a[0]到a[i-1]中比它小的所有元素依次有序地交换。在索引i由左向右变化的过程中,它左侧的元素总是有序的,所以当i到达数组的右端时排序就完成了。

InsertSort_2:
要大幅提高插入排序的速度并不难,只需要在内循环中将较大的元素都向右移动而不总是交换两个元素(这样访问数组的次数就能减半)。

以上是关于算法(第4版) C++ 插入排序的优化的主要内容,如果未能解决你的问题,请参考以下文章

算法(第4版) C++ 实现各种排序算法(未完成)

图解算法系列之插入排序(优化版)

直接插入排序算法——Java实现

算法(第4版)-2.5 应用

基于比较的七种常见排序算法

基于比较的七种常见排序算法