java 二分查找法
发布网友
发布时间:2022-04-19 19:43
我来回答
共2个回答
热心网友
时间:2023-09-05 09:53
public class BinarySearch {
public static void main(String[] args) {
int[] a = { 2, 4, 6, 9 };
int key = 2;
BinarySearchM(a, key);
System.out.println("The key is in " + BinarySearchM(a, key));
}
public static int BinarySearchM(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
System.out.println(mid);
if (key < list[mid])//mid 改为 list[mid]
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return -low - 1;
}
}
热心网友
时间:2023-09-05 09:53
package test;
public class Search {
public Search() {
}
/**
* @param data 从小到大排好序的数组
* @param goal 要查找的数
* @param left
* @param right
* @return 目标数的数组下标,没有找到为-1 ;
*/
public static int find(int[] data,int goal,int left,int right) {
int mid = (left+right)/2 ;
if(left>right) {
return -1 ;
}
if(goal==data[mid]) {
return mid ;
}
else if(goal<data[mid]) {
//注意right = mid -1 ;
return find(data,goal,left,mid-1);
}
else if(goal>data[mid]) {
return find(data,goal,mid+1,right);
}
return -1 ;
}
public static void main(String[] args) {
int[] data = new int[] {1,2,4,6,7};
int result =find(data,6,0,data.length-1) ;
System.out.println(result);
}
}
希望能解决您的问题。