package dataStructures;
import java.util.Scanner;
/*
用二分法在一个有序数列{1,2,3,4,5,6,7,8,9,10}中查找key值,
若找到key则输出其在数组中对应的下标,否则输出not found。
*/public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};//数组
int key = scanner.nextInt();//查找值
scanner.close();
int weizhi = BinarySearch(array, key);
if (weizhi == -1) {
System.out.println("not found");
} else {
System.out.println("weizhi:" + weizhi);
}
}
private static int BinarySearch(int[] array, int key) {
int low = 0;
int high = array.length-1;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (array[mid] == key) {
return mid;
} else if (array[mid] > key) {
high = mid - 1;
} else {
low = mid + 1;
}
}
return -1;
}
}
Java二分法查找数组中某个数的下标
最新推荐文章于 2024-07-27 04:47:31 发布