迫于考试,请教各位大佬一个 Java 二分查找算法

2021-04-15 15:32:56 +08:00
 KissFace
题目:给定一个递增排序的数组,查找某个数字是否在数组中,如果在数组中,则返回该数字在数组中第一次出现的位置(从 0 开始);如果不在数组中,返回-1 。务必使用二分查找的方式

哪位好心人可以贴下代码
427 次点击
所在节点    问与答
4 条回复
uselessVisitor
2021-04-15 20:45:44 +08:00
这不就是二分查找吗?百度一下都有
uselessVisitor
2021-04-15 21:04:17 +08:00
public static int binarySearch(int[] arrays, int key, int start, int end) {
if (key < arrays[start] || key > arrays[end] || start > end) {
return -1;
}
int mid = (start + end) / 2;
if (arrays[mid] > key) {
return binarySearch(arrays, key, start, mid - 1);
} else if (arrays[mid] < key) {
return binarySearch(arrays, key, mid + 1, end);
} else {
return mid;
}
}
uselessVisitor
2021-04-15 21:06:32 +08:00
jdk 的写法
// Like public version, but without range checks.
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex;
int high = toIndex - 1;

while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];

if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
KissFace
2021-04-16 13:51:57 +08:00
@beichenhpy 谢谢老哥

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/770872

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX