|
| 1 | +import java.util.Scanner; |
| 2 | + |
| 3 | +/** |
| 4 | + * Implements a Binary Search in Java |
| 5 | + * |
| 6 | + * @author unknown |
| 7 | + */ |
| 8 | +class BinarySearch |
| 9 | +{ |
| 10 | + /** |
| 11 | + * This method implements the Binary Search |
| 12 | + * |
| 13 | + * @param array The array to make the binary search |
| 14 | + * @param key The number you are looking for |
| 15 | + * @param lb The lower bound |
| 16 | + * @param up The upper bound |
| 17 | + * @return the location of the key |
| 18 | + **/ |
| 19 | + public static int BS(int array[], int key, int lb, int ub) |
| 20 | + { if (lb>ub) |
| 21 | + { |
| 22 | + return -1; |
| 23 | + } |
| 24 | + |
| 25 | + int mid=(lb+ub)/2; |
| 26 | + |
| 27 | + if (key<array[mid]) |
| 28 | + { |
| 29 | + return (BS(array, key, lb, mid-1)); |
| 30 | + } |
| 31 | + else if (key>array[mid]) |
| 32 | + { |
| 33 | + return (BS(array, key, mid+1, ub)); |
| 34 | + } |
| 35 | + else |
| 36 | + { |
| 37 | + return mid; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | + /** |
| 43 | + * This is the main method of Binary Search |
| 44 | + * |
| 45 | + * @author Unknown |
| 46 | + * @param args Command line parameters |
| 47 | + */ |
| 48 | + |
| 49 | + public static void main(String[] args) |
| 50 | + { |
| 51 | + Scanner input=new Scanner(System.in); |
| 52 | + int array[]=new int[10] ; |
| 53 | + int key; |
| 54 | + |
| 55 | + //Input |
| 56 | + System.out.println("Enter an array of 10 numbers : "); |
| 57 | + for (int i=0; i<10 ;i++ ) |
| 58 | + { |
| 59 | + array[i]=input.nextInt(); |
| 60 | + } |
| 61 | + System.out.println("Enter the number to be searched : "); |
| 62 | + key=input.nextInt(); |
| 63 | + |
| 64 | + int index=BS(array, key, 0, 9); |
| 65 | + if (index!=-1) |
| 66 | + { |
| 67 | + System.out.println("Number found at index number : " + index); |
| 68 | + } |
| 69 | + else |
| 70 | + { |
| 71 | + System.out.println("Not found"); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments