书上的二分查找是定义了一个有序数组,然后二分查找返回一个bool类型,我这里写的是随便输入一个数组,二分查找,找到了返回位置,找不到输出“找不到”
package bbb;
import java.util.Scanner;
public class Binary {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int k = 1;
System.out.println("输入个数");
int n = reader.nextInt();
Stu[] s = new Stu[500];
System.out.println("输入值");
for (int i = 0; i < n; i++) {
s[i] = new Stu();
s[i].v = reader.nextInt();
s[i].t = k;
k++;
}
//你这里没有输入要查找的数字
System.out.println("輸入要查找的数字");
int m = reader.nextInt();
//冒泡排序
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (s[j].v > s[j + 1].v) {
swap(s[j], s[j + 1]);
}
}
}
if (binarySort(s,n,m) == -1) {
System.out.println("找不到");
} else {
System.out.println("找到了,在第" + s[binarySort(s, n,m)].t + "个位置");
}
}
public static void swap(Stu x, Stu y) {
Stu temp;
temp = x;
x = y;
y = temp;
}
public static int binarySort(Stu[] source,int n, int key) {
int low = 0;
int high =n - 1; //n为输入的个数
while (low <= high) {
int mid = (low + high) / 2;
int midVal = source[mid].v;
if (midVal < key) {
low = mid + 1;
} else if (midVal > key) {
high = mid;
} else {
return mid;
}
}
return -1;
}
}
class Stu {
int v,t = 0;// v为值 t为位置
}
这个小算法期间除了很多问题,非常感谢dota2吧的各位大哥照顾我这个小萌新,给我耐心解答哈哈~