排序
1.插入排序(增量方法)
将已排序的定义在最左端,将未排序的部分取最左边第一个元素,插入在已经排序部分的最合适的位置
当然,也可以将已排序的定义在最右端,从未排序的部分取最右边的一个元素,插入到最右边最合适的位置
// 从最左到最右边,从第二个元素开始,对比第一个元素。再从第三个元素开始,与前面两个元素对比,依次下去
// 第n个元素作为key,前面1~n-1已经排序好了,先与n-1进行比对,发现合适,就不用与n-2进行对比了
// 发现比n-1小,说明前面肯定有它的坑位,n-1肯定要往后挪一个位置,再将key与n-2对比,如果发现还小,说明n-2也要往后挪动
// 比如打扑克牌,开始手上没有扑克,来一张把它放到最合适位置,再来一个,先与最边上对比,找到最适合位置
int sort_min_1(int* ptr_source, int len)
{
int j = 1;
int i = j - 1;
for (; j < len; ++j)
{
int key = ptr_source[j];
i = j - 1;
while (ptr_source[i] > key && i >= 0)
{
// if ptr_source[i] is small than key,ptr_source[i-1] is too small
// so you can leave the while
ptr_source[i+1] = ptr_source[i];
--i;
}
ptr_source[i+1] = key;
}
}
// 从最右边开始
int sort_min_2(int* ptr_source, int len)
{
// sort from len to 0
int j = len - 2;
int i = j + 1;
for (; j >= 0; --j)
{
i = j + 1;
int key = ptr_source[j];
while(ptr_source[i] < key && i > 0 && i < len)
{
ptr_source[i-1] = ptr_source[i];
++i;
}
ptr_source[i-1] = key;
}
}
// 最大的在最前面
int sort_max_1(int* ptr_source, int len)
{
// sort from max to min
// sort from 0 to len
int j = 1;
int i = j - 1;
for (; j < len; ++j)
{
i = j - 1;
int key = ptr_source[j];
while(ptr_source[i] < key && i >= 0)
{
ptr_source[i+1] = ptr_source[i];
--i;
}
ptr_source[i+1] = key;
}
}
int sort_max_2(int* ptr_source, int len)
{
// sort from max to min
}
算法分析
最好的情况,已经排序好,只需要for遍历一遍即可,算法为线性的,(O(n))
最坏的情况,刚好是反序的,for中while也需要全部遍历,算法为O(n^2)。我们一般只考虑最坏的情况,它是一个上界。