代码如下:
#include <iostream>
using namespace std;
void insertSort(int a[], int n)
{
for(int i=1;i<n;++i)
{
if(a[i]<a[i-1])
{
int low = 0;
int high = i-1;
int j;
int temp = a[i];
while(low<=high)
{
int mid=(low+high)/2;
if(a[mid]==a[i])
{//将a[i]放在a[mid]右边
for( j=i-1;j>mid;--j)
{
a[j+1]=a[j];
}
a[mid+1] = temp;
}
else if(a[mid]<a[i])
{
low=mid+1;
}
else
{
high=mid-1;
}
}
if(low>high)/*说明当前插入的元素不在已排好序的数列中,此时应该将元素放在index等于low处,或者index等于high+1处;*/
{
for( j=i-1;j>=low;--j)
{
a[j+1]=a[j];
}
a[low] = temp;
}
}
}
}
int main()
{
const int N=7;
int a[]={3,1,7,9,2,5,4};
insertSort(a,N);
for(int i=0;i<N;++i)
{
cout<<a[i]<<" "<<endl;
}
return 0;
}