java二分法查找

时间:2022-05-06
本文章向大家介绍java二分法查找,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
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);
	}
}