问题描述
给定一个n个有序的(升序)整型数组nums和一个目标值target,写一个二分查找函数搜索nums中的target,如果目标值存在则返回下标,否则返回-1。
代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] temp = scanner.nextLine().trim().split(" ");
int[] arr = new int[temp.length];
for (int i = 0; i < arr.length; i++) {
arr[i] = Integer.parseInt(temp[i]);
}
int target = scanner.nextInt();
System.out.println(search(arr, target));
}
public static int search(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int mid = (left + right) / 2;
while (left <= right) {
if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
return mid;
}
mid = (left + right) / 2;
}
return -1;
}
}