public class search {
public static void main(String[] args) {
int[] a = new int[] {1, 2, 3, 4, 5, 6};
binarySearch(a, 3);
binarySearch(a, 7);
}
// 二分查找
public static boolean binarySearch(int[] array, int n) {
int l = 0, r = array.length - 1;
int mid = (l + r) / 2;
while(l <= r) {
if(array[mid] > n) {
r = mid - 1;
} else if(array[mid] < n) {
l = mid + 1;
} else {
System.out.println("找到"+n+"在索引"+mid);
return true;
}
mid = (l + r) / 2;
}
System.out.println("找不到"+n);
return false;
}
}
二分查找
最新推荐文章于 2024-08-16 23:08:28 发布