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;
}
}
数据结构与算法(JAVA版)1_2:二分法例题
最新推荐文章于 2022-04-03 13:24:34 发布