Java 二分查找算法优化:查找小于最大值和大于最小值元素
以下是使用Java编写的改写后的二分搜索算法,以满足题目要求:
public class BinarySearch {
public static int[] binarySearch(int[] a, int x) {
int n = a.length;
int i = 0;
int j = n - 1;
while (i <= j) {
int mid = i + (j - i) / 2;
if (a[mid] == x) {
return new int[]{mid, mid};
}
if (a[mid] < x) {
i = mid + 1;
} else {
j = mid - 1;
}
}
return new int[]{j, i};
}
public static void main(String[] args) {
int[] a = {10, 20, 30, 40, 50, 60, 70};
int x = 35;
int[] result = binarySearch(a, x);
System.out.println('Index of element smaller than x: ' + result[0]);
System.out.println('Index of element greater than x: ' + result[1]);
}
}
在main函数中,我们定义了一个已排好序的数组a和要搜索的元素x。然后调用binarySearch方法进行搜索,并将结果存储在result数组中。最后,将小于x的最大元素的索引和大于x的最小元素的索引打印出来。
请注意,上述代码假设数组a已经按升序排好序。如果数组a是按降序排列的,则需要对代码进行相应的修改。
原文地址: https://www.cveoy.top/t/topic/bpRu 著作权归作者所有。请勿转载和采集!