Home ICSE Computer Applications Class 10 – Previous Year Question Papers & Solutions / Programs / Define a class 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". 2, 5, 7, 10, 15, 20, 29, 30, 46, 50
🚀 Programming Example

Define a class 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".

2, 5, 7, 10, 15, 20, 29, 30, 46, 50

👁 79 Views
💻 Practical Program
📘 Step Learning
Learn this program step-by-step with algorithm, source code, output and detailed explanation.
No previous program
No next program

📌 Information & Algorithm

Given Input:


Expected Output:


💻 Program Code

import java.util.Scanner;

public class RansariBinarySearch
{
    public static void main(String args[]) {
        
        Scanner in = new Scanner(System.in);
        int arr[] = {2, 5, 7, 10, 15, 20, 29, 30, 46, 50};
        
        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);
        }
    }
}
                        
No previous program
No next program
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.