折半排序(binary insert sort )也是插入排序的一种,只是这种适合于数据很少的时候的一种排序方法,相比于直接的插入排序,折半排序减少了“比较”,和“移动”这两种步骤.
算法思想还是二分法
#include <iostream>
using namespace std;
void BinarySort(int a[],int length)
{
for(int i=1;i<length;i++)
{
int low=0;
int high=i-1;
int temp=a[i];
while(low<=high)
{
int m=(low+high)/2;
if(a[i]>a[m]) low=m+1;//如果点在右侧
else high=m-1;//点在左侧
}
for(int j=i-1;j>=high+1;j--)
{
a[j+1]=a[j];//后移
}
a[high+1]=temp;//插入
}
}
int main()
{
int a[5]={2,4,5,7,1};
BinarySort(a,5);
for(int i=0;i<5;i++)
{
cout<<a[i]<<" ";
}
}