import java.util.Arrays;
public class Test {
int test[] = {49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18,23,34,15,35,25,53,51,111,222,333,444,546,768};
public void test() {
//排序
Arrays.sort(test);
//二分查找
int result = binarySearch1(test,12);
System.out.println("index = "+result);
}
public int binarySearch0(int[] a,int key) {
return binarySearchImpl0(a,key,0,a.length-1);
}
public int binarySearch1(int[] a,int key) {
return binarySearchImpl1(a,key,0,a.length-1);
}
/*先用递归实现*/
private int binarySearchImpl0(int[] a,int key,int lowindex,int highindex) {
/*int[] a是经过排序的数组,通常是升序排列,如果key超出范围,直接返回,函数只处理在范围内的查找不到的异常*/
if( key > a[highindex] || key < a[lowindex] ) {
return -1;
}
if( lowindex > highindex ) {
return -1;
}
int midindex = (lowindex+highindex)>>>1;
if( key < a[midindex] ) {
return binarySearchImpl0(a,key,lowindex,midindex-1);
} else if( key > a[midindex] ) {
return binarySearchImpl0(a, key, midindex+1, highindex);
} else {
return midindex;
}
/*小结:
* 1、递归法的好处是函数逻辑结构简单
* 2、缺点是如果数组体量很大,可能会造成函数栈溢出
* 制造栈溢出的方法:1、申请一个大的local变量 2、深度递归*/
}
/*使用循环实现*/
private int binarySearchImpl1(int[] a,int key,int lowindex,int highindex) {
int midindex = 0;
int low = lowindex;
int high = highindex;
/*循环截止条件:lowindex > highindex*/
while( low <= high ) {
midindex = (low+high) >>>1;
if( key < a[midindex] ) {
high = --midindex;
} else if( key > a[midindex] ) {
low = ++midindex;
} else {
return midindex;
}
}
return -1;
}
}
【代码积累-2】binary search
最新推荐文章于 2023-08-22 21:30:00 发布