Binary Search Java Program | ISC Computer Science 2020 Theory

Design a class BinSearch to search for a particular value in an array.

Some of the members of the class are given below:

Class name: BinSearch
Data members/instance variables:
arr[]: to store integer elements
n: integer to store the size of the array
Member functions/methods:
BinSearch(int nn): parameterized constructor to initialize n = nn
void fillarray(): to enter elements in the array
void sort(): sorts the array elements in ascending order using any standard sorting technique
int bin_search(int l, int u, int v): searches for the value ‘v’ using binary search and recursive technique and returns its location if found otherwise returns -1

Define the class BinSearch giving details of the constructor(), void fillarray(), void sort() and int bin_search(int, int, int). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
class BinSearch{
    int arr[];
    int n;
    public BinSearch(int nn){
        n = nn;
        arr = new int[n];
    }
    public void fillarray(){
        System.out.println("Enter array elements:");
        Scanner in = new Scanner(System.in);
        for(int i = 0; i < n; i++)
            arr[i] = Integer.parseInt(in.nextLine());
    }
    public void sort(){
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n - i - 1; j++){
                if(arr[j] > arr[j + 1]){
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    public int bin_search(int l, int u, int v){
        if(l > u)
            return -1;
        int m = (l + u) / 2;
        if(v == arr[m])
            return m;
        if(v > arr[m])
            return bin_search(m + 1, u, v);
        return bin_search(l, m - 1, v);
    }
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Number of elements: ");
        int size = Integer.parseInt(in.nextLine());
        BinSearch obj = new BinSearch(size);
        obj.fillarray();
        obj.sort();
        System.out.print("Element to be searched: ");
        int key = Integer.parseInt(in.nextLine());
        int i = obj.bin_search(0, size - 1, key);
        if(i == -1)
            System.out.println(key + " not found.");
        else
            System.out.println(key + " found at index " + i);
    }
}