插入排序
插入排序是算法导论中介绍的第一个简单排序算法
它的流程可以用洗扑克牌来类比:
现在你的手上有一些乱序的扑克牌,要将其进行排序
先抽出手上的最后一张牌,然后倒着寻找第一张比它小的牌,并插入在那张牌后面
接下来重复以上流程,直到所有扑克牌有序为止
例子:
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]