Binary Search Program in Java With Step-by-Step Dry Run

⚑ Direct Answer & Key Takeaway

Binary Search locates a target key inside an already sorted array by repeatedly dividing the active search window in half. Starting with `low = 0` and `high = n - 1`, it calculates `mid = (low + high) / 2` and checks `arr[mid]`. If `arr[mid] == key`, the search succeeds immediately; if `key > arr[mid]`, `low` shifts to `mid + 1`; otherwise `high` shifts to `mid - 1`, stopping when `low > high`.

1. Mandatory Sorted Array Precondition & Midpoint Logic

Before writing a single loop, remember Binary Search's iron rule: the array must already be sorted in ascending (or known descending) order. If an ICSE question provides an unsorted array, sort it first or verify whether the prompt specifies 'given in ascending order'β€”many board questions supply pre-sorted arrays of years of graduation or item codes directly. At each iteration of `while (low <= high)`, Java computes integer division `mid = (low + high) / 2` (or `low + (high - low) / 2` to prevent integer overflow on massive arrays), dropping any `.5` decimal fraction. Because `arr[mid]` has already been checked, excluding it via `mid + 1` or `mid - 1` guarantees the search window shrinks every step and never loops forever.

  • Loop condition MUST be `low <= high` (with `<=`), because a single-element window where `low == high` can still hold `key`.
  • For a descending-sorted array, swap the pointer updates: move `high = mid - 1` when `key > arr[mid]`, and `low = mid + 1` when `key < arr[mid]`.
  • Use `int pos = -1;` as a sentinel flag so you can distinguish 'found at index 0' from 'not found'.
  • Integer division `(3 + 4) / 2` evaluates to `3` in Java, always truncating toward zero.

2. Step-by-Step Dry Run on {10, 18, 25, 34, 42, 56, 71, 88}

Suppose `arr = {10, 18, 25, 34, 42, 56, 71, 88}` (`n = 8`) and we search for `key = 56`. In Step 1, `low = 0` and `high = 7` yield `mid = (0 + 7) / 2 = 3`. Because `arr[3]` is `34` and `56 > 34`, Java discards indices `0..3` and sets `low = 4`. In Step 2, `low = 4` and `high = 7` give `mid = 5`, where `arr[5] == 56`, so `pos = 5` and `break` finishes in two checks. If instead `key = 30`, probes visit `mid = 3` (`34`), `mid = 1` (`18`), and `mid = 2` (`25`), after which `low` becomes `3`, breaking `low <= high` and reporting not found.

  • Successful hit (`key = 56`): `mid = 3` (`34 < 56`) -> `mid = 5` (`56 == 56`), found at index `5` (position `6`).
  • Unsuccessful miss (`key = 30`): `mid = 3 -> mid = 1 -> mid = 2`, then `low (3) > high (2)` terminates the loop.
  • Even on `1,024` sorted items, Binary Search checks at most `11` elements (`log2(1024) + 1`).

3. ICSE Board Variations: Graduation Years & String Binary Search

CISCE board exams rarely ask a bare integer search without contextβ€”famous Section B questions include searching an array of graduation years `{1982, 1987, 1993, 1996, 1999, 2003, 2006, 2007, 2009, 2010}` and printing `'Record exists'` or `'Record does not exist'`, or searching a sorted `String[]` of city names. For pre-populated arrays in the question paper, initialize the array directly with `{...}` instead of reading `n` values via `Scanner`, and read only the search key from the user. When binary searching strings, replace `arr[mid] == key` with `arr[mid].equalsIgnoreCase(key)` and test `key.compareToIgnoreCase(arr[mid]) > 0` to move `low = mid + 1`.

  • Check whether the question expects `Record exists` / `Record does not exist` or the 1-based position (`pos + 1`).
  • If the question provides a fixed sorted list, hardcode `{...}` and take only the target value with `Scanner`.
  • Never write `low = mid` or `high = mid`; omitting `+ 1` or `- 1` causes an infinite loop when `key` is absent.

4. BinarySearchICSE.java (Iterative Sorted-Array Search)

import java.util.*;

public class BinarySearchICSE {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int[] arr = {10, 18, 25, 34, 42, 56, 71, 88};

        System.out.print("Enter element to search: ");
        int key = sc.nextInt();

        int low = 0, high = arr.length - 1, pos = -1;

        while (low <= high) {
            int mid = (low + high) / 2;
            if (arr[mid] == key) {
                pos = mid;
                break;
            } else if (key > arr[mid]) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        if (pos != -1) {
            System.out.println("Search Successful! Element found at index " + pos);
        } else {
            System.out.println("Search Unsuccessful! Element not found.");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter element to search: 56
Search Successful! Element found at index 5

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
arr[]int[]Pre-sorted ascending array searched via Binary Search (Sample: {10, 18, ..., 88})
keyintTarget integer entered by the user to search (Sample: 56)
lowintLower boundary index of current search range (Sample: 0 -> 4)
highintUpper boundary index of current search range (Sample: 7)
midintMiddle index calculated as (low + high) / 2 each step (Sample: 3 -> 5)
posintStores matched index or remains -1 when key is absent (Sample: 5)
🎯 1-on-1 Live Mentorship & Free Study Kit

Practice Binary Search Dry Runs & Board Programs 1-on-1

Get guided BlueJ practice tracing low, high, and mid pointers on real CISCE specimen questions so you never miss edge-case marks in Section A or Section B.

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Writing `while (low < high)` instead of `while (low <= high)`, which fails to check the last remaining element when `low` and `high` meet.
  • Avoid Mistake: Updating `low = mid` or `high = mid` without `+ 1` / `- 1`, causing an infinite loop when the searched key is not in the array.
  • Avoid Mistake: Applying Binary Search directly to an unsorted array, which discards the half containing the target key and reports false misses.
  • Examiner / Mentor Tip: When asked for a graduation-year Binary Search in Section B, initialize the sorted array directly from the question and only input the target year.
  • Examiner / Mentor Tip: Always initialize `pos = -1` (never `pos = 0`), because index `0` is a valid position where the first array element can be found.
  • Examiner / Mentor Tip: In Section A dry-run questions, write out `low`, `high`, `mid`, and `arr[mid]` in a neat trace column for every iteration until `break` or `low > high`.

7. Interactive Concept Check Quiz

Question: Using Binary Search on {5, 12, 19, 24, 31, 45, 58} for key = 19, which sequence of mid indices is checked before finding 19?

8. Frequently Asked Questions

What happens if you run Binary Search on an unsorted array in Java?
Binary Search does not throw a compiler or runtime error on unsorted data, but it gives wrong answers. Because it discards half the array assuming monotonic order, the target element may sit inside the discarded half and never be inspected. Always sort an unsorted array with Bubble or Selection Sort before Binary Searching.
Can Binary Search work on an array containing duplicate values?
Yes, standard Binary Search finds one matching index of the duplicate key and stops when arr[mid] == key. However, it does not guarantee returning the first or last occurrence unless you continue narrowing left or right after a match. For counting total frequency of duplicates, Linear Search is simpler and exact.
Why is mid = (low + high) / 2 safe in ICSE programs, and when does overflow happen?
In ICSE school programs where array sizes are small (like 10 to 100 elements), (low + high) / 2 is completely safe and expected by examiners. Integer overflow only occurs when low + high exceeds Integer.MAX_VALUE (over 2.14 billion), where professional Java uses low + (high - low) / 2 instead.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class