class find{
public static void main(String args[]){
int x[] = {22,33,44,55,66,77,88};
int search = searchValue2(x,55);
System.out.println("["+search+"]");
}
public static int searchValue(int x[],int search){
int max = x.length - 1;
int min = 0;
int avg = (max+min)>>>1;
while(x[avg] != search){
if(search>x[avg]){
min = avg+1;
}
else if(search<x[avg]){
max = avg-1;
}
if(min>max)
return -1;
avg = (max+min)>>>1;
}
return avg;
}
public static int searchValue2(int x[],int search){
int max = x.length-1;
int min = 0;
int avg = (max+min)>>>1;
while(max>=min){
if(search > avg){
min = avg+1;
}
else if(search < avg){
max = avg-1;
}
else
return avg;
avg = (max+min)>>>1;
}
return -1;
}
}
只要不是取中间标识位的数就都OK,一取中间标识位的数就成-1了~~~ |
|