算法描述:从第二个值开始向左查找,找到适合的位置插入。实现过程是:如果找到比它本身大的交换,如果找到比它小的,插在该值的后面。
时间复杂度:平均时间复杂度为O(n2),输入的数据越有序,速度越快。最快可以达到线性时间O(n)。
代码如下:
#include <iostream>
using namespace std;
void InsertionSort(int a[], int n)
{
for(int i = 1; i < n; i++)
{
int key = a[i];
int j = i-1;
while(j >= 0 && a[j] > key)
{
a[j+1] = a[j];
j--;
}
a[j+1] = key;
}
}
int main()
{
int n;
int a[1000];
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
InsertionSort(a, n);
for(int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
return 0;
}
实现的时候出现了一点小错误,开始的时候对边界值考虑不周,导致最小元素无法插入第一个位置。