insertion sorting
有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,要求插入此数据后,序列仍然有序。
每次插入一个数据,就需要和序列中的其他数据作比较,所以时间复杂度是 O(n^2)。这么大的时间复杂度,很明显这个排序适合用来做少量数据的排序。
插入排序是稳定排序,也就是说,两个相同元素,在排序后前后没发生变化。
最差情况:反序,需要移动n*(n-1)/2个元素 。
最好情况:正序,不需要移动元素。
有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,要求插入此数据后,序列仍然有序。
每次插入一个数据,就需要和序列中的其他数据作比较,所以时间复杂度是 O(n^2)。这么大的时间复杂度,很明显这个排序适合用来做少量数据的排序。
插入排序是稳定排序,也就是说,两个相同元素,在排序后前后没发生变化。
最差情况:反序,需要移动n*(n-1)/2个元素 。
最好情况:正序,不需要移动元素。
空间复杂度是O(1).
#include<iostream>
using namespace std;
/*****
function insertsort to sort
********/
void insertsort(int a[],int n)
{
for(int i = 0; i < n; i++)
{
//the value of a[i] will be changed ,so record it in tmp
int tmp = a[i],j = i;
//make a space for the new element
while(j > 0 && a[j - 1] > tmp)
{
a[j] = a[j - 1];
j--;
}
//insert the number to the ordered list
a[j] = tmp;
}
}
/*****
main function to check
********/
int main()
{
int n,a[101];
cin>>n;
for(int i =0; i < n; i++)
{
cin>>a[i];
}
insertsort(a,n);
for(int i =0; i < n; i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}