Source Code for Binary Search Algorithm

Output:

*** Binary Search Algorithm ***

Enter number of elements: 5
Enter 5 numbers in ascending order: 1 5 9 14 17

Enter value to find: 9
9 found at location 3.

Click Here For Java Online Compiler

Solution:

import java.util.Scanner;

class BinarySearch {

    public static void main(String args[]) {
        int c, first, last, middle, n, search, array[];

        Scanner in = new Scanner(System.in);
        System.out.println("*** Binary Search Algorithm ***" + "\n");
        System.out.print("Enter number of elements: ");
        n = in.nextInt();
        array = new int[n];

        System.out.print("Enter " + n + " numbers in ascending order: ");

        for (c = 0; c < n; c++) {
            array[c] = in.nextInt();
        }

        System.out.print("\nEnter value to find: ");
        search = in.nextInt();

        first = 0;
        last = n - 1;
        middle = (first + last) / 2;

        while (first <= last) {
            if (array[middle] < search) {
                first = middle + 1;
            } else if (array[middle] == search) {
                System.out.println(search
                        + " found at location " + (middle + 1) + ".");
                break;
            } else {
                last = middle - 1;
            }

            middle = (first + last) / 2;
        }
        if (first > last) {
            System.out.println(search
                    + " is not present in the list.\n");
        }
    }
}
Share This :

Related Post



sentiment_satisfied Emoticon