public class binaryfind {//折半查找  时间复杂度(O(log n))
public static void binary(int a[],int n,int key){
int low=1,high=n,mid;
while(low<=high){
mid=(low+high)/2;
//mid=low+(high-low)*(key-a[low))/(a[high]-a[low]);/*插值公式,效率更优*/
if(key<a[mid]){
high=mid-1;
}else if(key>a[mid]){
low=mid+1;
}else{
System.out.println(mid);
System.out.println(a[mid]);
break;
}
}
}
public static void main(String[] args) {
int a[]={0,1,16,24,35,47,59,62,73,89,99};
binary(a,10,24);

}

}

数据结构之 二分查找及用二分优化的插入排序 java_i++

代码如下:

public class insertsort2 {
public void print(int a[]){
for(int x: a){
System.out.print(x+" ");
}
System.out.println();
}
public void binaryInsertSort(int a[]){ //用二分优化的插入排序
//依次把每个元素拿来插入到之前的有序子序列(从第二个开始,到最后就行)
for(int i=0;i<a.length-1;i++){//趟数,每趟插入第i+1个元素---待插入的数
int temp=a[i+1];//先把待插入的数备份到temp中

//利用二分算法找到一个位置high
int low=0;//左边界
int high=i;//右边界
int mid;//中间位置
while(low<=high){
//计算mid,让mid和temp比较,决定temp是落在左半区或右半区
mid=(low+high)/2;
if(a[mid]>temp){//落在左半区,更改右边界
high=mid-1;
}else{//落在右半区,更改左边界
low=mid+1;
}
}
//经过上面一段,找到temp将要放置的位置high+1
for(int j=i;j>high;j--){//把high+1到i这些元素全部后挪一个位置
a[j+1]=a[j];
}

//让temp坐在high+1位置
a[high+1]=temp;
}
print(a);
}
public static void main(String[] args) {
int a[]={-3,4,8,16,21,23,25,25,45,49};
new insertsort2().binaryInsertSort(a);
}
}

数据结构之 二分查找及用二分优化的插入排序 java_折半查找_02