您的位置:首页 > 编程语言 > Java开发

java二分法查找

2012-10-01 00:00 309 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java二分法查找