直接插入排序算法C++实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hello_ape/article/details/73518813

最近开始学习算法导论,这篇文章就当作学习开篇了,有些简单的算法就只给出代码实现了,详细的介绍相信大家都能掌握,此标签下的算法都是以C++语言实现。

算法的伪代码如下,理解下思想

INSERTION-SORT(A)

for j=2 to A.length

key=A[j]

//insert A[j] into the sorted sequenceA[1.....j-1]

i=j-1

       while i>0and A[i]>key

A[i+1]=A[i]

                i=i-1

      A[i+1]=key

废话不多说,直接上代码。

#include "iostream"
#define MAX_SIZE  10	//假设10个数字排序
using namespace std;

int main(){

	int a[MAX_SIZE];
	cout << "init 数组" << endl;
	for (int i = 0; i <MAX_SIZE;i++)     //自己随便输入
	{
		cin >> a[i];
	}

	for (auto c : a)					//遍历输出,查看正确性
		cout << c << " ";
	cout << endl;
	int i, j;
	int temp;							 //定义一个变量,用于交换存储临时值
	for ( i = 1; i < MAX_SIZE; i++)      //从数组第二个开始比较,默认第一个是有序的
	{
		temp = a[i];					 //保留当前待排序的数值
		
		for ( j = i - 1; j >= 0; j--)
		{
			if (temp < a[j])             //如果要插入的数据小于有序的,则有序的向右调整
			{
				a[j + 1] = a[j];
				
			}
			else                         //找到插入点,结束内层循环
				break;
		}
		a[j + 1] = temp;				 //j+1 才是插入的点
	}
	for (auto c : a)					
		cout << c << " ";
	cout << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hello_ape/article/details/73518813