Binary Search Method




Program In Java To Search The Given Element Using Binary Search Method.

The Following Program Reads The Elements Of An Array From User in Ascending Order And Then It Searches The Key Element In Array Using Binary Search Method And Displays The Position Of The Key Element. If Key Element Is Not Found It Displays Key Not Found

import java.io.*;
class Binary {
    int binarySer(int[] a, int k) {
        int low, upper, mid;
        low = 0;
        upper = a.length - 1;
        for (mid = (low + upper) / 2; low <= upper; mid = (low + upper) / 2) {
            if (k == a[mid]) 
              return mid;
            if (k > a[mid]) 
              low = mid + 1;
            else 
              upper = mid - 1;
        }
        return -1;
    }
    public static void main(String[] arg) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter Total Number Of Elements In An Array::");
        int t = Integer.parseInt(br.readLine());
        int[] arr = new int[t];
        System.out.println("\nEnter Array Elements In Ascending Order::");
        for (int i = 0; i < t; i++) {
            System.out.print("\nEnter Element::");
            int e = Integer.parseInt(br.readLine());
            arr[i] = e;
        }
        System.out.println("\n\nEntered Array Is::");
        for (int i = 0; i < arr.length; i++) {
            System.out.print("\t" + arr[i]);
        }
        System.out.print("\n\nEnter Key Element To Found::");
        int key = Integer.parseInt(br.readLine());
        //int []arr={12,23,24,35,36,56,67,78,87};
        //int key=78;
        Binary b = new Binary();
        int r = b.binarySer(arr, key);
        if (r >= 0) 
          System.out.println("\n\n\tKey Found At Position Number " + r);
        else 
          System.out.println("\n\n\tKey Not Found");
    }
}


OUTPUT:


Enter Total Number Of Elements In An Array::9
Enter Array Elements In Ascending Order::

Enter Element::12

Enter Element::23

Enter Element::24

Enter Element::35

Enter Element::36

Enter Element::56

Enter Element::67

Enter Element::78

Enter Element::87

Entered Array Is::
12 23 24 35 36 56 67 78 87

Enter Key Element To Found::78

Key Found At Position Number 7
Previous Post Next Post