一、基本思路:将一个待排序的记录,按照关键字大小插入到前面已经拍好的子序列的适当位置,直到全部记录插入完成为止。
如果序列基本有序,效率很高。
二、代码
#include "stdafx.h"
#include<stdlib.h>
#include<iostream>
using namespace std;
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
void insertSort(int a[], int n)
{
for (int j=1;j<n;j++)
{
for(int k=j-1;k>=0;k--)
{
if(a[k]>a[k+1])
{
swap(a[k],a[k+1]);
}
}
}
}
int main(int argc,char* argv[]){
int n;
int a[10000];
while(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;
}
system("pause");
return 0;
}
3、结果分析
时间复杂度o(n)-o(n^2)
空间复杂度o(1)
稳定