java二分法查找

原创
2012/10/01 18:56
阅读数 153
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);
	}
}

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部