方式一:递归实现二分查找
解释:
arr int型数组elemen 需要查找的元素left 数组的左下标(初始值为0 )right 是数组的右下标(初始值为数组长度减一(arr.length-1 ))
public static int binarySearch(int[] arr, int element, int left, int right) {
if (element < arr[left] || element > arr[right] || left > right) {
return -1;
}
int middle = left + ((right - left) / 2);
if(arr[middle] == element) return middle;
if (arr[middle] > element) {
return binarySearch(arr, element, left, middle - 1);
} else if (arr[middle] < element) {
return binarySearch(arr, element, middle + 1, right);
} else {
return middle;
}
}
方式二:简单判断(if…else)实现二分查找
解释:
array int型数组element 所要查找的元素
public static int search(int[] array,int element) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int middle = left + ((right - left) / 2);
if (array[middle] == element)
return middle;
if (array[middle] > element) {
right = middle - 1;
} else if (array[middle] < element) {
left = middle + 1;
} else {
return middle;
}
}
return -1;
}
|