概述
1.假设有一个数组 { 12, 23, 34, 45, 56, 67, 77, 89, 90 },现要求采用二分法找出指定的数值并将其在数组的索引返回,如果没有找到则返回 -1。代码如下:
package cn.sunzn.dichotomy;
public class DichotomySearch {
public static void main(String[] args) {
int[] arr = new int[] { 12, 23, 34, 45, 56, 67, 77, 89, 90 };
System.out.println(search(arr, 12));
System.out.println(search(arr, 45));
System.out.println(search(arr, 67));
System.out.println(search(arr, 89));
System.out.println(search(arr, 99));
}
public static int search(int[] arr, int key) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int middle = (start + end) / 2;
if (key < arr[middle]) {
end = middle - 1;
} else if (key > arr[middle]) {
start = middle + 1;
} else {
return middle;
}
}
return -1;
}
}
最后
以上就是简单芹菜为你收集整理的采用二分法的全部内容,希望文章能够帮你解决采用二分法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复