//折半查找,二分查找,
public class BinarySearch {
public static int binarySearch(int[] a, int x){
int low = 0;
int high = a.length - 1;
while(low <= high){
int mid = (low + high) / 2;
if(a[mid] > x)
high = mid - 1;
else if(a[mid] < x)
low = mid + 1;
else
return mid;
}
return -1;
}
public static void main(String[] args){
int[] b = {1,5,6,7,8,9,12,46,166,544,44444};
//int x = 646;
int x = 12;
int index = binarySearch(b,x);
System.out.println(x +" b["+ index +"] = "+ b[index]);
}
}
折半查找,二分查找,
最新推荐文章于 2022-12-10 20:48:47 发布