给定一个有序整型数组, 实现二分查找
程序员文章站
2024-03-17 14:43:28
...
问题描述:给定一个有序整型数组, 实现二分查找
import java.util.Scanner;
import java. util. Arrays;
public class binaryTest {
public static void main (String[] args) {
//输入需查找的数字
Scanner scanner = new Scanner(System. in);
int num = scanner.nextInt();
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};
//调用并输出
System. out. println(binarySearch(arr, num));
}
//二分查找
public static int binarySearch(int[] arr, int toFind) {
int left = 0;
int right = arr.length - 1;
//当left <= right 时合法
while(left <= right){
int mid = (left + right) / 2;
//左侧区域查找
if(toFind < arr[mid]){
right = mid - 1;
}
//右侧区域查找
else if(toFind > arr[mid]){
left = mid + 1;
}
//找到值并返回
else{
return mid;
}
}
//没找到时,返回-1
return -1;
}
}
测试数据:toFind = 6;
下标为5;
结果如下:
上一篇: PAT A1010 Radix