public static void main(String[] args) {
/*
* 折半查找:可以用来比较快速的查找某个值的索引位置
* 1.先规定一个最小的索引min=0和最大的索引max=arr.length-1
* 2.取mid=(min+max)/2
* 3.中间索引的值与value比较
* 大了:max=mid-1;
* 小了:min=mid+1;
* 4.重复2
*/
int[] arr = { 12, 14, 15, 17, 25, 30, 42, 45, 50 };
int value = 333;
int index = getIndex(arr, value);
System.out.println(index);
}
public static int getIndex(int[] arr, int value) {
int min = 0;
int max = arr.length - 1;
int mid = (min + max) / 2;
while (arr[mid] != value) {
if (arr[mid] > value) {
max = mid - 1;
} else if (arr[mid] < value) {
min = mid + 1;
}
if(min > max){
return -1;
}
mid = (min + max) / 2;
}
return mid;
}
/*
* 折半查找:可以用来比较快速的查找某个值的索引位置
* 1.先规定一个最小的索引min=0和最大的索引max=arr.length-1
* 2.取mid=(min+max)/2
* 3.中间索引的值与value比较
* 大了:max=mid-1;
* 小了:min=mid+1;
* 4.重复2
*/
int[] arr = { 12, 14, 15, 17, 25, 30, 42, 45, 50 };
int value = 333;
int index = getIndex(arr, value);
System.out.println(index);
}
public static int getIndex(int[] arr, int value) {
int min = 0;
int max = arr.length - 1;
int mid = (min + max) / 2;
while (arr[mid] != value) {
if (arr[mid] > value) {
max = mid - 1;
} else if (arr[mid] < value) {
min = mid + 1;
}
if(min > max){
return -1;
}
mid = (min + max) / 2;
}
return mid;
}