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

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);
           
	}

}


代码如下:

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);
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值