二分搜索的java实现


/* ---------------------------------------------------------------
 * author: xujin, 4100213
 * date: Oct 17, 2012
 * binarySearch
 * to search a number in an array by using binarySearch algorithm
 * example: binarySearch([1,2,3,4,5,6,7,8], 3, 8)
 * to produce 2 
 *---------------------------------------------------------------*/

import java.util.Scanner;

class BinSearch{
	public static int binarySearch(int a[], int x, int n){
		int left = 0;
		int right = n - 1;
		while(left <= right){
			//int middle = (left + right)/2;
			int middle = left + (right - left)/2;
			if(x == a[middle]) return middle;
			if(x > a[middle]) left = middle + 1;
			else right = middle - 1;
		}
		return -1;
	}
} 

public class xujin_4100213_BinarySearch {
	static Scanner cin = new Scanner(System.in);	
	public static void main(String[] args){
		System.out.print("Please input a integer(the size of array): 

");			
		int sizeOfArray = cin.nextInt();  
		int a[] = new int[sizeOfArray];	
		System.out.print("Please input " + sizeOfArray + " sorted 

numbers: ");
		for(int i = 0; i < sizeOfArray; i++) 
			a[i] = cin.nextInt();			
		System.out.print("Please input the number you want to search: 

");
		int x = cin.nextInt();   
		System.out.print("Location: " + BinSearch.binarySearch(a, x, 

sizeOfArray));
	}	
}




你可能感兴趣的:(二分搜索的java实现)