直接插入排序原理可以在网上搜到,这里给出C++实现。分为带“哨兵”和不带“哨兵”两种
/*************************************************************************
> File Name: InsertSort.cpp
> Author: Shorey
> Mail: shoreybupt@gmail.com
> Created Time: 2015年04月08日 星期三 10时22分21秒
************************************************************************/
#include<iostream>
using namespace std;
void InsertSort1(int a[],int n)//不带哨兵的插入排序
{
int key;
int j;
for(int i=1; i<n; i++)
{
key=a[i];
for(j=i-1; key<a[j]&&j>=0; j--)
{
a[j+1]=a[j];
}
a[j+1]=key;
}
}
void InsertSort2(int a[],int n)//带哨兵的插入排序,需要传入的数组的第0号位置的留空设置哨兵,否则,需要把传入的数组重新放入一个n+1的数组中再排序
{
for(int i=2;i<=n;i++)
{
a[0]=a[i];
int j;
for(j=i-1; a[0]<a[j];j--)
a[j+1]=a[j];
a[j+1]=a[0];
}
}
int main()
{
int a[7]={
-1,4,2,5,1,6,0
};
InsertSort2(a,6);
return 0;
}