//二分法 排序(面试宝典上的)
//二分法排序原理:构造二叉树,小的在左,大的在右,将待排序的数依次插入,然后前序遍历即可。
//利用二叉树的构造把每个数插入到适当的位置。
//时间复杂度:O(n2)
//为稳定排序
public class binarySort {
public static void main(String []args){
int a[]={4,6,2,5,8,1,9,7,0,3};
binarySort(a);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
public static void binarySort(int a[]){
int temp;
int low,high,mid;
int i,j;
for(i=1;i<a.length;i++){//算法实质为:以a[i]为基准,对其前面的序列使用二分法进行排序,并在此过程中找到a[i]的位置,插入进去。
temp=a[i];//要比较的元素
low=0;//二分法开始
high=i-1;//二分法结束
while(low<=high){//和中间值比较,由此缩小查找范围
mid=(low+high)/2;//二分
if(temp<a[mid]){// 和中间值比较,比较并逐渐缩小范围;;;和中间值比较啊
high=mid-1;//将高指针重新定位
}else{
low=mid+1;//将低指针重新定位
}
}
for(j=i-1;j>high;j--){//查找到插入位置,将其后面元素后移,
a[j+1]=a[j];
}
a[high+1]=temp;//将元素插入到序列中
}
}
}