Insertion sort: For every piece of data coming in from the outside of the queue, compare it with the ordered queue starting from the maximum value. After finding a suitable position, move the ordered queue and insert the new data into the corresponding position.
code and debugging results:
#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;
}
Time complexity of insertion sort:
Number of comparisons: 1 + 2 + 3 ... + (N-2) + (N-1) = N^2/2-N/2
Number of exchanges: 1 + 2 + 3 ... + (N-2) + (N-1) = N^2/2-N/2
The total number of times is: N^2-N
According to the Big O derivation rule, the final time complexity is O(N^2)