插入排序:从队列外边每进来一个数据,跟已序队列从最大值开始比较,找到合适的位置后, 移动已序队列,并将新来的数据插入到对应的位置。
code 和 调试结果:
#include <iostream>
using namespace std;
template <class T>
void insert_sort(T list[],int n)
{
T in, out,tmp;
for (out = 1; out < n; out++) //out从下标1开始的,第0个已经提前出来放好了
{
in = out;
tmp = list[out];
while (in > 0 && list[in - 1] > tmp)
{
list[in] = list[in - 1]; //移动已序队列
in--;
}
list[in] = tmp;
}
}
int main()
{
int arry[10] = {5,6,2,7,3,1,9,0,4,8};
insert_sort<int>(arry,sizeof(arry)/sizeof(arry[0]));
for (int i = 0; i < sizeof(arry) / sizeof(arry[0]); i++)
cout << arry[i] << " ";
cout << endl << endl << endl;
return 0;
}
插入排序的时间复杂度:
比较的次数: 1 + 2 + 3 ... + (N-2) +(N-1) = N^2/2 - N/2
交换的次数: 1 + 2 + 3 ... + (N-2) +(N-1) = N^2/2 - N/2
总次数为:N^2-N
按照大O推导法则,最终时间复杂度为O(N^2)
扫描二维码关注公众号,回复:
12530620 查看本文章