public class binarySearch {
int binarysearch(int[] a, int x) {
int low = 0;
int high = a.length - 1;
int mid;
while(low <= high) {
mid = (low + high) / 2;
if(a[mid] < x) {
low = mid + 1;
}
else if(a[mid] > x) {
high = mid - 1;
}
else {
return mid;
}
}
return -1;
}
int binarySearchRecursive(int[] a, int x, int low, int high) {
if (low > high) return -1;
int mid = (low + high) / 2;
if(a[mid] < x) {
return binarySearchRecursive(a, x, mid + 1, high);
}
else if (a[mid] > x) {
return binarySearchRecursive(a, x, low, mid - 1);
}
else {
return a[mid];
}
}
}
【Java】二分查找
最新推荐文章于 2022-06-09 07:48:32 发布