package cqu.edu.lk;
public class BinarySearch {
public static void main(String[] args) {
int[] test = {1,2,3,4,5,6,7,8,9};
int loc1 = binarySearch(test,3);
int loc2 = binarySearch(test,3,0,test.length-1);
System.out.println("3的位置在"+loc1);
System.out.println("3的位置在"+loc2);
}
/*
* @param a
* 查找的数组,前提必须是排好序的数组
* @param key
* 目标字,要查找的字
*/
public static int binarySearch(int[] a,int key){
int high = a.length-1;
int low = 0;
int mid;
while(low<high){
mid = (low+high)/2;
if(key<a[mid]){
high = mid-1;
}
else if(key>a[mid]){
low = mid+1;
}
else{
return mid;
}
}
return -1;
}
/*
* 递归算法,每一个循环都可以写成递归
* 默认数组是升序
*/
public static int binarySearch(int[] a,int key,int startSearch,int endSearch){
int mid = (startSearch+endSearch)/2;
if(startSearch>endSearch||key<a[startSearch]||key>a[endSearch]){
return -1;
}
if(a[mid]>key){
return binarySearch(a, key,startSearch,mid-1);
}
else if(a[mid]<key){
return binarySearch(a, key,mid+1,endSearch);
}
else{
return mid;
}
}
}
算法Java第一天(二分查找)
最新推荐文章于 2015-12-16 01:45:18 发布