在排序数组中查询指定数字

//注意查询边界以及正序逆序判断

package com.test;



public class Test {

public static int search(int arr[],int len,int target){
if(len < 1){
return -1;
}
int first = 0;
int last = len-1;
while(first <= last){
int mid = (first+last)/2;
if(target == arr[mid]){
return mid;
}
if(arr[first] < arr[mid]){
if(target>=arr[first] && target<arr[mid]){
last = mid - 1;
}else{
first = mid + 1;
}
}else{
if(target>arr[mid] && target<=arr[first]){
last = mid - 1;
}else{
first = mid + 1;
}
}
}
return -1;
}


public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hello java!");
int temp[] = {10,9,8,7,6,5,4,3,2,1,0};
int index = Test.search(temp, 11, 0);
System.out.println(index);
}


}

猜你喜欢

转载自blog.csdn.net/ysh126/article/details/80780604