插入排序的方法:
不断将无序队列的元素加入到有序队列中。
直接插入排序
源码
template <class T>
//insert_sort
int sort(T *t, int n)
{
int compare_times = 0;
for(int i=1; i<n; i++)
{
T current = t[i];
for(int k=i-1; k>=0; k--)
{
compare_times++;
if(t[k] > current)
{
t[k+1] = t[k];
if(k == 0)
t[k] = current;
}
else
{
t[k+1] = current;
break;
}
}
}
return compare_times;
}
执行结果
时间复杂度
o(n2)
最好的时间复杂度(已经有序的情况下):
o(n)
空间复杂度
o(1)
折半插入排序
折半插入排序利用了二分查找的优点:查找到元素的位置速度更快。
源码
template <class T>
//half_insert_sort
int sort(T *t, int n)
{
int compare_times = 0;
for(int i=1; i<n; i++)
{
T current = t[i];
int s=0, e=i-1;
//找出第i个元素应该在的位置position
int position;
while(e > s)
{
compare_times++;
//舍去法取整,必须先加1,否则会出错
position = (e + s + 1) / 2;
if(t[position] < current)
s = position + 1;
else if(t[position] > current)
e = position - 1;
else
s = e = position;
}
if(t[e] > current)
position = e;
else
position = s + 1;
//比current大的元素整体向后移一位
for(int k=i; k>position; k--)
{
t[k] = t[k-1];
}
t[position] = current;
}
return compare_times;
}
执行结果
比较次数减少了,移动次数未变。