排序算法——插入排序

插入排序

插入排序是算法导论中介绍的第一个简单排序算法

它的流程可以用洗扑克牌来类比:
现在你的手上有一些乱序的扑克牌,要将其进行排序
先抽出手上的最后一张牌,然后倒着寻找第一张比它小的牌,并插入在那张牌后面
接下来重复以上流程,直到所有扑克牌有序为止

例子:

5 3 8 7 1 9 4 2 6
5 3 8 7 1 2 9 4 6  // 6 is bigger than 2, and 2 is smaller than 1
5 3 8 7 1 2 4 9 6  // 6 is bigger than 4, and 4 is smaller than 9
5 3 8 7 1 2 4 6 9  // 9 is bigger than 6
1 5 3 8 7 2 4 6 9  // 2 is bigger than 1, and 1 is smaller than 7
1 2 5 3 8 7 4 6 9  // 4 is bigger than 2, and 2 is smaller than 7
1 2 5 3 4 8 7 6 9  // 6 is bigger than 4, and 4 is smaller than 7
1 2 5 3 4 6 8 7 9  // 9 is bigger than 6, and 6 is smaller than 7
1 2 5 3 4 6 7 8 9  // 9 is bigger than 7, and 7 is smaller than 8
1 2 3 5 4 6 7 8 9  // 4 is bigger than 3, and 3 is smaller than 5
1 2 3 4 5 6 7 8 9  // 6 is bigger than 4, and 4 is smaller than 5
// every factory is bigger than the one before him, finish insertSort

在最坏的情况下,即将倒序的数组变为正序,对于第i个元素(0<=i<=n-1),需要进行至多n次交换才能使其到达对应的位置,总共有n个元素,因此时间复杂度为 O ( n 2 ) O(n^2) O(n2)
并没有使用多余的空间进行存储,因此空间复杂度为 O ( 1 ) O(1) O(1)

(我们很快就会发现上面的关于时间复杂度的推导极其草率)

给出实现算法:

void insertSort_1(int *array, int start, int end)
{
   
	int i = end;
	while(i > start)
	{
   
		int tmp = array[i];  // 抽出来的卡
		int j = i - 1;
		while(j >= start && array[j] > tmp)
		{
   
			array[j + 1] = array[j];  // 右移
			j -= 1;
		}
		array[j + 1] 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值