图解插入排序

插入排序(升序):稳定,时间复杂度 O(n^2)

具体实现思路如图:

具体实现代码如下:

void InsertSort(int *a ,int len)
{
	if (len <= 1)
	{
		return;
	}
	int count = 1;
	for (; count < len; count++)
	{
		int tmp = a[count];
		int cur = count;
		for (; cur>0; cur--)
		{
			if (a[cur - 1] >tmp)
			{
				a[cur] = a[cur - 1];
			}
			else
			{
				break;
			}
			a[cur - 1] = tmp;
		}
	}
}
int main()
{
	int a[5] = { 5, 3, 4, 2, 1 };
	InsertSort(a, (sizeof(a) / sizeof(a[0])));
	for (int i = 0; i < 5; i++)
	{
		printf("%d", a[i]);
	}
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/enjoymyselflzz/article/details/81226422