数据结构与算法(JAVA版)1_2:二分法例题

package com.inspire.chapter1;

public class Dichotomy {

	public static void main(String[] args) {
		int[] a={1,2,3,4,5,6,7,8,9,10};
		//第一题:查找有序数组a中是否存在元素2
		boolean res=exist(a,2);
		System.out.println(res);
		//第二题:查找有序数组a中元素value最左侧的数据
		int value=5;
		int index=nearestIndex(a,value);
		System.out.println(value+"最左侧的值是:"+index);
		//第三题:查找无序数组a局部最小值的下标
		int[] a2={5,4,2,3,6,1,10,7,8,9};
		int i=getLessIndex(a2);
		System.out.println("局部最小值的小标为:"+i);
	}
	private static int getLessIndex(int[] a) {
		if(a==null||a.length==0){
			return -1;//不存在
		}
		if(a.length==1||a[0]<a[1]){
			return 0;
		}
		if(a[a.length-1]<a[a.length-2]){
			return a.length-1;
		}
		int L=1;
		int R=a.length-2;
		int mid=0;
		while(L<R){
			mid=(L+R)/2;
			if(a[mid]>a[mid-1]){
				R=mid-1;
			}else if(a[mid]>a[mid+1]){
				L=mid+1;
			}else{
				return mid;
			}
		}
		return L;
	}
	//在数组上找满足>=value的最左位置,要求数组有序
	private static int nearestIndex(int[] a, int value) {
		int L=0;
		int R=a.length-1;
		int index=-1;
		while(L<=R){
			int mid=L+((R-L)>>1);
			if(a[mid]>=value){
				index=mid;
				R=mid-1;
			}else{
				L=mid+1;
			}
		}
		return index;
	}
	
	//查找数组中是否存在数num,要求数组有序
	private static boolean exist(int[] a, int num) {
		if(a==null||a.length==0){
			return false;
		}
		int L=0;
		int R=a.length-1;
		int mid=0;
		while(L<R){
			mid=L+((R-L)>>1);
			if(a[mid]==num){
				return true;
			}else if(a[mid]>num){
				R=mid-1;
			}else{
				L=mid+1;
			}
		}
		return a[L]==num;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Inspiration666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值