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…

ICSE Class 10 Computer Applications PYQ · 2010 Paper · Section B

4Written · 2010 · Section B · 2010 Paper

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

Show SolutionHide Solution↓
import java.util.Scanner;

public class KboatBinarySearch
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        int arr[] = {5, 7, 9, 11, 15, 20, 30, 45, 89, 97};
        
        System.out.print("Enter number to search: ");
        int n = in.nextInt();
        
        int l = 0, h = arr.length - 1, index = -1;
        while (l <= h) {
            int m = (l + h) / 2;
            if (arr[m] < n)
                l = m + 1;
            else if (arr[m] > n)
                h = m - 1;
            else {
                index = m;
                break;
            }
                
        }
        
        if (index == -1) {
            System.out.println("Search element not found");
        }
        else {
            System.out.println(n + " found at position " + index);
        }
    }
}
BlueJ output of KboatBinarySearch.java BlueJ output of KboatBinarySearch.java
← Previous questionNext question →

Browse the free Computer Applications sample bank