ISC 2020 Computer Science Theory Binary Search Program

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 num): parameterized constructor to initialize n = num.
void fillArray(): to enter elements in the array.
void sort(): sorts the array elements in ascending order using any standard sorting technique.
int binSearch(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 binSearch(int, int, int). Define the main() function to create an object and call the functions accordingly to enable the task.

import java.io.*;
class BinSearch{
    int arr[];
    int n;
    public BinSearch(int num){
        n = num;
        arr = new int[n];
    }
    public void fillArray()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter array elements:");
        for(int i = 0; i < n; i++)
            arr[i] = Integer.parseInt(br.readLine());
    }
    public void sort(){
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n - 1 - i; j++){
                if(arr[j] > arr[j + 1]){
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    public int binSearch(int l, int u, int v){
        int mid = (l + u) / 2;
        if(v == arr[mid])
            return mid;
        else if(l > u)
            return -1;
        else if(v > arr[mid])
            return binSearch(mid + 1, u, v);
        else
            return binSearch(l, mid - 1, v);
    }
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter array size: ");
        int num = Integer.parseInt(br.readLine());
        BinSearch obj = new BinSearch(num);
        obj.fillArray();
        obj.sort();
        System.out.print("Enter value to be searched: ");
        int value = Integer.parseInt(br.readLine());
        int index = obj.binSearch(0, num - 1, value);
        if(index == -1)
            System.out.println(value + " not found.");
        else
            System.out.println(value + " found at index " + index);
    }
}

4 thoughts on “ISC 2020 Computer Science Theory Binary Search Program”

  1. Sir,how to create Java applets in sublime text editor? can you please show me a sample program as well as the steps?

    Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: