对一个数组进行二分查找为什么奇数偶数没影响
答案:1 悬赏:50 手机版
解决时间 2021-12-26 05:34
- 提问者网友:欺烟
- 2021-12-25 05:19
对一个数组进行二分查找为什么奇数偶数没影响
最佳答案
- 五星知识达人网友:空山清雨
- 2021-12-25 06:31
public class BinarySearchDemo {
public static void main(String[] args) {
int[] a = new int[]{1,5,7,9,11,18,23,48,69};
int point = new BinarySearchDemo().binarySearch(a, 23);
if(point == -1)
System.out.println("在数组中未查找到数23");
else
System.out.println("数字23是数组中第 " + (point + 1) + " 位数");
}
public int binarySearch(int[] a,int num){
int low = 0;
int high = a.length - 1;
while(low <= high){
int middle = (low + high) / 2;
if(num == a[middle])
return middle;
else if(num < a[middle])
high = middle - 1;
else
low = middle + 1;
}
return -1;
}
}
程序基本上就是这样了,其中注释中有详细的解释说明
public static void main(String[] args) {
int[] a = new int[]{1,5,7,9,11,18,23,48,69};
int point = new BinarySearchDemo().binarySearch(a, 23);
if(point == -1)
System.out.println("在数组中未查找到数23");
else
System.out.println("数字23是数组中第 " + (point + 1) + " 位数");
}
public int binarySearch(int[] a,int num){
int low = 0;
int high = a.length - 1;
while(low <= high){
int middle = (low + high) / 2;
if(num == a[middle])
return middle;
else if(num < a[middle])
high = middle - 1;
else
low = middle + 1;
}
return -1;
}
}
程序基本上就是这样了,其中注释中有详细的解释说明
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯