首先找到数组的分割点然后按照二分查找即可。
数组的分割点也可以按照二分查找来,不过需要修改一下地方。
package sf1_4;
/**
* Created by LoveQuietly on 2016/9/7.
*/
public class DoubleSearch {
public static void main(String[] args) {
int []a={1,5,6,7,9,23,12,9,7,5,3,2,1};
getPosition(a,2);
}
/**
* 用来查找数据分割点
* @param a
* @return
*/
public static int getThePoint(int[] a) {
int lo = 0;
int high = a.length - 1;
int mid = 0;
//当lo==high的时候已经找到了位置
while (lo < high) {
//上划线
mid = lo + (high - lo) / 2;
//升序
if (a[mid] < a[mid + 1]) {
lo = mid + 1;
//降序
} else if (a[mid] < a[mid - 1]) {
high = mid-1;
}else
return mid;
}
return lo;
}
//测试代码
public static int getPosition(int[] a, int key) {
int pos=getThePoint(a);
int t=binaryUp(a,0,pos,key);
System.out.println(t);
if (t!=-1)
return -1;
int t1=binaryDown(a,pos+1,a.length-1,key);
System.out.println(t1);
return -1;
}
//降序的时候二分查找
public static int binaryDown(int[] a, int lo, int high, int key) {
int mid = 0;
while (lo <= high) {
mid = lo + (high - lo) / 2;
if (a[mid] < key) {
high = mid - 1;
} else if (a[mid] == key) {
return mid;
} else {
lo = mid + 1;
}
}
return -1;
}
//升序的时候二分查找
public static int binaryUp(int []a,int lo,int high,int key){
int mid=0;
while(lo<=high){
mid=lo+(high-lo)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key){
high=mid-1;
}else
lo=mid+1;
}
return -1;
}
}