Binary Search in Java

Write a class BinaryDemo to perform binary search on an array of integers. The description of the class is given below:

Class name: BinaryDemo
Data members:
a[]: stores N integers.
key: stores the integer that has to be searched.
Member functions:
sortArray(): to sort the array using bubble sort.
searchArray(): to perform binary search on the array, and display appropriate message.

Also define the main() method to create an object and call the methods accordingly to enable the task.

Program:

import java.io.*;
class BinaryDemo{
    private int a[];
    private int key;
    public void sortArray()throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        a = new int[n];
        System.out.println("Enter " + n + " elements:");
        for(int i = 0; i < a.length; i++)
            a[i] = Integer.parseInt(br.readLine());
        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a.length - 1 - i; j++){ 
                if(a[j] > a[j + 1]){
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }
    public void searchArray()throws IOException{
        int low = 0;
        int high = a.length - 1;
        int mid = 0;
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("Key: ");
        key = Integer.parseInt(br.readLine());
        while(low <= high){
            mid = (low + high) / 2;
            if(key == a[mid])
                break;
            else if(key < a[mid]) 
                high = mid - 1; 
            else 
                low = mid + 1; 
        } 
        if(low > high)
            System.out.println(key + " not found.");
        else
            System.out.println(key + " found.");
    }
    public static void main(String args[])
    throws IOException{
        BinaryDemo obj = new BinaryDemo();
        obj.sortArray();
        obj.searchArray();
    }
}

Leave a Reply

%d bloggers like this: