永发信息网

用Java语言编写对整型数组进行二分查找的程序。

答案:3  悬赏:0  手机版
解决时间 2021-03-31 09:15
  • 提问者网友:动次大次蹦擦擦
  • 2021-03-30 18:27
用Java语言编写对整型数组进行二分查找的程序。
最佳答案
  • 五星知识达人网友:迷人又混蛋
  • 2021-03-30 18:43
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;
}

}

程序基本上就是这样了,其中注释中有详细的解释说明
全部回答
  • 1楼网友:风格不统一
  • 2021-03-30 20:34
用Arrays的静态方法binariSearch方法就行了。
  • 2楼网友:英雄的欲望
  • 2021-03-30 20:22
二分查找要求数组事先排好序
import java.util.*;
public class MyBinary {
public static void main(String args[]) {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int key;// 声明要查找的数据
Scanner in = new Scanner(System.in);// 声明Scanner对象,可由键盘输入数据
System.out.print("数组为:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("请输入你要查找的数据:");
key = in.nextInt();// 获得由键盘输入的数据
int i = new MyBinary().search(array, key);
if (i == -1) {
System.out.println("没有找到" + key + "!");
} else {
System.out.println("找到,下标为" + i);
}
}
public int search(int[] number, int key) {
int left = 0;
int right = number.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (number[mid] < key)
left = mid + 1;
else if (number[mid] > key)
right = mid - 1;
else
return mid;
}
return -1;
}
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯