2017-04-18 22:57:17 +08:00
|
|
|
import java.util.Scanner;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Implements a Binary Search in Java
|
|
|
|
*
|
|
|
|
* @author unknown
|
|
|
|
*/
|
|
|
|
class BinarySearch
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* This method implements the Binary Search
|
|
|
|
*
|
|
|
|
* @param array The array to make the binary search
|
|
|
|
* @param key The number you are looking for
|
|
|
|
* @param lb The lower bound
|
|
|
|
* @param up The upper bound
|
|
|
|
* @return the location of the key
|
|
|
|
**/
|
|
|
|
public static int BS(int array[], int key, int lb, int ub)
|
2017-07-16 16:28:01 +08:00
|
|
|
{
|
|
|
|
if ( lb > ub)
|
2017-04-18 22:57:17 +08:00
|
|
|
return -1;
|
2017-07-16 16:28:01 +08:00
|
|
|
|
|
|
|
int mid = (lb + ub) / 2;
|
2017-04-18 22:57:17 +08:00
|
|
|
|
2017-07-16 16:28:01 +08:00
|
|
|
if (key < array[mid])
|
2017-04-18 22:57:17 +08:00
|
|
|
return (BS(array, key, lb, mid-1));
|
2017-07-16 16:28:01 +08:00
|
|
|
|
|
|
|
if (key > array[mid])
|
|
|
|
return (BS(array, key, mid + 1, ub));
|
|
|
|
|
|
|
|
return mid;
|
2017-04-18 22:57:17 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This is the main method of Binary Search
|
|
|
|
*
|
|
|
|
* @author Unknown
|
|
|
|
* @param args Command line parameters
|
|
|
|
*/
|
|
|
|
|
|
|
|
public static void main(String[] args)
|
|
|
|
{
|
|
|
|
Scanner input=new Scanner(System.in);
|
|
|
|
int array[]=new int[10] ;
|
|
|
|
int key;
|
|
|
|
|
|
|
|
//Input
|
|
|
|
System.out.println("Enter an array of 10 numbers : ");
|
2017-07-16 16:28:01 +08:00
|
|
|
|
|
|
|
for (int i = 0; i < 10 ; i++ )
|
|
|
|
array[i] = input.nextInt();
|
|
|
|
|
2017-04-18 22:57:17 +08:00
|
|
|
System.out.println("Enter the number to be searched : ");
|
2017-07-16 16:28:01 +08:00
|
|
|
|
|
|
|
key = input.nextInt();
|
2017-04-18 22:57:17 +08:00
|
|
|
|
|
|
|
int index=BS(array, key, 0, 9);
|
2017-07-16 16:28:01 +08:00
|
|
|
|
|
|
|
if (index != -1)
|
|
|
|
System.out.println("Number found at index number : " + index);
|
|
|
|
else
|
2017-04-18 22:57:17 +08:00
|
|
|
System.out.println("Not found");
|
2017-07-16 16:28:01 +08:00
|
|
|
|
2017-04-21 02:56:21 +08:00
|
|
|
input.close();
|
2017-04-18 22:57:17 +08:00
|
|
|
}
|
|
|
|
}
|