算法思路
利用二分法的思想,在一个有序的序列中,找到该元素在序列中的位置,然后将其插入。
其中,n个元素的数组需要进行n-1趟排序
算法实现
算法
public void BinaryInsertSort(int[] array){
int i,j,low,high,mid,temp;
for(i=1;i<array.length;i++){
temp=array[i];
low=0;
high=i-1;
while (low<=high){
mid=(low+high)/2;
if(array[mid]>temp)//如果当前中值还是大于temp
high=mid-1;//查看左半子表
else
low=mid+1;//查找右半子表
}
for(j=i-1;j>=high+1;--j){
array[j+1]=array[j];
}
array[j+1]=temp;
}
}
测试
/**折半插入排序*/
int[] array2=new int[]{1,0,1,5,9,8,2,7};
binaryInsertSort.BinaryInsertSort(array2);
System.out.println("-----------折半插入排序---------");
for (int i : array2) {
System.out.print(i+"、");
}
System.out.println();
结果
-----------折半插入排序---------
0、1、1、2、5、7、8、9、