Write a program to perform binary search on a list of integers given below to search for an element input by the user. If it is found, display the element along with its position; otherwise, display the message "Search element not found."
5, 7, 9, 11, 15, 20, 30, 45, 89, 97

Java Programming Language (Article) (Program)

65

Given Input:

5, 7, 9, 11, 15, 20, 30, 45, 89, 97

Expected Output:

15 found at position 5

Program:

class BSearch {
    int A[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97}; // Array of integers
    int low, high, mid, flag = 0; // Variables for binary search and flag for checking if element is found

    void display(int n) {
        low = 0; // Initialize low to the first index
        high = A.length - 1; // Initialize high to the last index
        
        while (low <= high) {
            mid = (low + high) / 2; // Calculate mid index
            
            if (n == A[mid]) { // If the element is found
                flag = 1;
                break;
            } else if (n > A[mid]) { // If the search element is greater, ignore the left half
                low = mid + 1;
            } else { // If the search element is smaller, ignore the right half
                high = mid - 1;
            }
        }
        
        if (flag == 1) {
            System.out.println(n + " found at position " + (mid + 1)); // Element found
        } else {
            System.out.println("Search element not found"); // Element not found
        }
    }
    
    public static void main(String args[]) {
        BSearch obj = new BSearch();
        obj.display(15); // Test the binary search with the element 15
    }
}

Output:

15 found at position 5

Explanation:

  1. Array Initialization:

    • int A[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97}; defines the array of integers to be searched.
  2. Binary Search Logic:

    • The low, high, and mid variables help in narrowing down the search range.
    • The search continues by comparing the middle element (A[mid]) with the target (n). Depending on whether n is greater or lesser, the search range is adjusted by modifying low or high.
  3. Flag for Element Found:

    • flag = 1; indicates that the element has been found, which breaks the loop.
  4. Output:

    • If the element is found, the program prints its position (1-based index).
    • If not found, it prints "Search element not found".

Key Points:

  • This program searches for the integer 15 in the array, but you can modify obj.display(15); to search for any other integer.
  • The position is based on a 1-based index (i.e., starting from 1).

This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.