problem
Let a[0:n-1] be the sorted array. Please rewrite the binary search algorithm so that when the search element x is not in the array, the largest element position i smaller than x and the smallest element position j larger than x are returned. When the search element is in the array, i and j are the same, and both are the positions of x in the array.
Code
Ordinary binary search
This scenario is the simplest, and probably the most familiar to everyone, that is to search for a number, if it exists, return its index, otherwise return -1.
int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1; // 注意
while(left <= right) {
// 注意
int mid = (right + left) / 2;
if(nums[mid] == target)
return mid;
else if (nums[mid] < target)
left = mid + 1; // 注意
else if (nums[mid] > target)
right = mid - 1; // 注意
}
return -1;
}
After improvement
package com.huang.binarySearch;
import java.util.Scanner;
public class BSearch {
static int[] binarySearch(int[] nums, int target) {
int[] info = new int[2];
int left = 0;
int right = nums.length - 1; // 注意
while (left <= right) {
// 注意
int mid = (right + left) / 2;
if (nums[mid] == target) {
info[0] = mid;
info[1] = mid;
return info;
} else if (nums[mid] < target) {
left = mid + 1; // 注意
info[0] = mid;
info[1] = left;
} else if (nums[mid] > target) {
right = mid - 1; // 注意
info[1] = mid;
info[0] = right;
}
}
return info;
}
public static void main(String[] args) {
int[] nums = {
1, 3, 5, 7, 9, 11, 13, 15};
System.out.print("存在数组nums=[");
for (int num : nums) {
System.out.print(num+" ");
}
System.out.println("]");
Scanner scanner = new Scanner(System.in);
//输入要查找的数
System.out.println("输入要查找的数");
int i = scanner.nextInt();
int[] info = BSearch.binarySearch(nums, i);
//确定区间
System.out.print(i+"所在位置区间[");
for (int n : info) {
System.out.print(n+" ");
}
System.out.print("]");
}
}
Run test
存在数组nums=[1 3 5 7 9 11 13 15 ]
输入要查找的数
5
5所在位置区间[2 2 ]
存在数组nums=[1 3 5 7 9 11 13 15 ]
输入要查找的数
4
4所在位置区间[1 2 ]
存在数组nums=[1 3 5 7 9 11 13 15 ]
输入要查找的数
0
0所在位置区间[-1 0 ]