java代码实现二分查找算法
import java.util.Scanner;
public class 二分查找 {
public static void main(String[] args) {
int a[] = {2, 4, 7, 18, 25,25,25, 34, 56, 68, 89,100};
System.out.println("打印原始数据:");
for (int i = 0; i < a.length; ++ i){
System.out.print(a[i] + " ");
}
System.out.println();
System.out.println("请输入要查找的整数:");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
int pos = 0;
pos = binaryFind(a, num);
if (-1 != pos)
System.out.println("所查整数在数组中的位置下标是:" + pos);
else
System.out.println("没找到待查数据!");
}
public static int binaryFind(int a[],int num){
int low,mid,high;
low = 0;
high = a.length - 1;
mid = (low+high)/2;
while (low<=high) {
if (num == a[mid]) {
return mid;
} else if (num > a[mid]) {
low = mid + 1;
mid = (low + high) / 2;
} else {
high = mid - 1;
mid = (low + high) / 2;
}
}
return -1;
}
}