package com.cn.search;
import java.util.Scanner;
public class BinarySearch {
public void binarySearch(int[] array, int search) {
int lower = 0, temp = array.length - 1, index = -1, currentValue = 0;
while (lower <= temp) {
index = (lower + temp) / 2;
currentValue = array[index];
if (currentValue == search)
break;
else if (currentValue > search)
temp = index - 1;
else
lower = index + 1;
}
if (lower <= temp)
System.out.println("你要查找的数为 " + currentValue + "。");
else
System.out.println("你要查找的数不存在。");
}
public static void main(String[] args) {
BinarySearch binarySearch = new BinarySearch();
int[] array = { 1, 5, 6, 9, 12, 23, 45, 56, 78, 89, 112, 123 };
System.out.println("Input the search number:");
Scanner scanner = new Scanner(System.in);
int search = scanner.nextInt();
binarySearch.binarySearch(array, search);
}
}