插入排序:
①直接插入排序。←this
②折半插入排序。
③2-路插入排序。
④表插入排序。
⑤希尔排序。
INSERTIONSORT,直接插入排序是一种最简单的排序方法,基本操作是将一个记录插入到已排好序的有序表,从而得到一个新的,记录数增1的有序表。
描述过程:将a[i]插入到a[ 1~i-1] 中的一个合适的位置上,从i-1逆向扫描到1(查找),不满足位置就向后移动,满足就插入。
伪代码:
输入:n个元素的数组A[1~n] 。
输出:按非降序排列的数组A[1~n]
for i ←2 to n
x ←A[i]
j ←i - 1
while(j>0) and (A[j]>x)
A[j+1] ←A[j]
j ←j-1
end while
A[j+1] ←x
end for
最好:已按非降序排序,比较次数为:n-1
最坏:元素已按降序排序,比较次数为:n(n-1)/2
时间复杂度:O(n2)
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int N=10;
void InsertSort(int *a,int st,int ed){
for(int i=st+1;i<ed;i++){
int x=a[i];
int j=i-1;
while( j>st-1 && a[j]>x ){
a[j+1]=a[j];
j=j-1;
}
a[j+1]=x;
}
}
int main()
{
int a[N]={5,6,3,2,1,8,9,7,4,10};
insertionsort(a,0,N);
for(int i=0;i<N;i++){
printf("%d ",a[i]);
}
return 0;
}