直接插入排序算法

算法思想:

 每一步将待排序的对象,按其关键码大小,插入到前面已经排好的一组对象的合适位置,

直到对象全部插入为止.

即边插入边排序.




给出实现代码:


#include <iostream>
using namespace std;

int main()
{
	int a[] = { 45, 65, 13, 25, 60, 88, 99, 78, 51, 37, 61, 50 };
	int k = sizeof(a) / sizeof(a[0]);

	int j;
	for (int i = 1; i < k; i++)  // 循环从第2个元素开始
	{
		if (a[i] < a[i - 1])
		{
			int temp = a[i];
			for (j = i - 1; j >= 0 && a[j] > temp; j--)
			{
				a[j + 1] = a[j];
			}
			a[j + 1] = temp;    // 在此处就就a[j+1]=temp
		}
	}

	for (int i = 0; i < k; i++)
	{
		cout << a[i] << "  ";
	}
	cout << endl;

	return 0;
}


猜你喜欢

转载自blog.csdn.net/Plus_L/article/details/80984159