public class Demo2_Array {
/**二分查找
*
*/
public static void main(String[] args) {
int[] arr = {11,22,33,44,55,66,77,88};
int i = -100;
System.out.println(getIndex(arr,i));
}
//这个是我自己写的
public static int getIndex(int[] arr,int value) {
int min = 0;
int max = arr.length - 1;
for(;;) {
int mid = (min + max) / 2;
if(value < arr[mid]) {
max = mid - 1;
}else if(value == arr[mid]) {
return mid;
}else if(value > arr[mid]) {
min = mid + 1;
}
if(max < min) {
return -1;
}
}
}
//这是老师写的
public static int getIndexTeach(int[] arr,int value) {
int max = arr.length - 1;
int min = 0;
int mid = (min + max) / 2;
while(value != arr[mid]) {
if(value > arr[mid]) {
min = mid + 1;
}else if(value < arr[mid]) {
max = mid - 1;
}
mid = (min + max) / 2;
if(max < min) {
return -1;
}
}
return mid;
}
}
|
|