Easy Array Problems Java

Binary Search in Java: Program and Logic

Return the index of a target in a sorted array, or -1 if it is missing.

  • TimeO(log n)
  • SpaceO(1)
  • Hints3
  • Read4 min
Quick answer

Binary search in Java works on a sorted array. Keep low and high, check the middle element, and drop the half that cannot hold the target. Stop when you find it or when low passes high. It takes O(log n) time and O(1) space in the loop version.

Binary searchSorted arrayDivide and conquer
1

Problem statement

Write a program for binary search in Java. Given an int array sorted in ascending order and a target, return an index where the target is found, or -1.

The array must be sorted. If it is not, use linear search or sort it first.

Input

A sorted integer array arr of length n and an integer target.

Output

An index of target, or -1.

Examples

Example 1
Inputarr = [5, 12, 18, 23, 31, 44, 59], target = 31
Output4

31 is at index 4.

Example 2
Inputarr = [5, 12, 18, 23, 31, 44, 59], target = 20
Output-1

20 would sit between 18 and 23, but it is not there.

Constraints

  • 0 <= n <= 10^6
  • arr is sorted in ascending order
  • With duplicates, any matching index is accepted
2

Think before you code

Reveal the questions to ask yourself first
  • If the middle value is too small, which half can you ignore?
  • When is the search range empty?
  • Why must mid itself be left out of the next range?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Start with low = 0 and high = n - 1.
2 Hint 2
Find the middle as low + (high - low) / 2 so that the sum cannot overflow.
3 Hint 3
Move to mid + 1 or mid - 1, never to mid, and loop while low <= high.
4

Approach

Reveal the step-by-step approach
  1. Set low = 0, high = n - 1.
  2. While low <= high, set mid = low + (high - low) / 2.
  3. If arr[mid] equals the target, return mid.
  4. If arr[mid] is smaller, search the right half: low = mid + 1.
  5. If it is larger, search the left half: high = mid - 1.
  6. If the loop ends, return -1.

Each step cuts the range by about half. For one million elements, at most 20 middle elements are checked, since 2²⁰ is a little over one million.

5

Dry run

Walk through the example step by step

Target 31 in [5, 12, 18, 23, 31, 44, 59]:

low | high | mid | arr[mid] | action
----+------+-----+----------+------------------
0   | 6    | 3   | 23       | 23 < 31, low = 4
4   | 6    | 5   | 44       | 44 > 31, high = 4
4   | 4    | 4   | 31       | found, return 4
6

Solution

Reveal the full Java solution
Solution.java
public class BinarySearch {
    static int search(int[] arr, int target) {
        int low = 0;
        int high = arr.length - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == target) {
                return mid;
            }
            if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {5, 12, 18, 23, 31, 44, 59};
        System.out.println(search(arr, 31));
        System.out.println(search(arr, 20));
        System.out.println(search(new int[0], 5));
    }
}

Output of this binary search in Java code:

4
-1
-1

Binary search in Java without function

Some exams want everything inside main. Scanner reads the size, the sorted elements, and then the target.

import java.util.Scanner;

public class BinarySearchMain {
    // Sample input: 5 10 20 30 40 50 40
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }
        int target = sc.nextInt();
        int low = 0, high = n - 1, pos = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (arr[mid] == target) {
                pos = mid;
                break;
            } else if (arr[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        System.out.println(pos == -1 ? "Not found" : "Found at index " + pos);
    }
}

Output for the sample input:

Found at index 3

Recursive binary search in Java program

public class BinarySearchRecursive {
    static int search(int[] a, int target, int low, int high) {
        if (low > high) {
            return -1;
        }
        int mid = low + (high - low) / 2;
        if (a[mid] == target) {
            return mid;
        }
        return a[mid] < target
                ? search(a, target, mid + 1, high)
                : search(a, target, low, mid - 1);
    }

    public static void main(String[] args) {
        int[] a = {2, 4, 6, 8, 10};
        System.out.println(search(a, 8, 0, a.length - 1));
        System.out.println(search(a, 7, 0, a.length - 1));
    }
}
3
-1

First match in a binary search in Java array with duplicates

Keep the answer, but continue on the left side.

public class FirstMatch {
    static int firstIndex(int[] a, int target) {
        int low = 0, high = a.length - 1, ans = -1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            if (a[mid] >= target) {
                if (a[mid] == target) {
                    ans = mid;
                }
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(firstIndex(new int[]{1, 4, 4, 4, 9}, 4));
    }
}
1

Binary search in Java: time complexity

Case Time Why
Best O(1) Target is the first middle element
Average and worst O(log n) The range halves each step

The loop uses O(1) extra space. The recursive version uses O(log n) stack space.

In real projects, Arrays.binarySearch(arr, target) does this for you. If the value is missing it returns a negative number that is not always -1, so test for >= 0.

To put data in order first, see insertion sort or merge sort. For interview practice, use the DSA interview questions. You can also learn Java step by step in the Java full stack course.

TimeO(log n)
SpaceO(1)
7

Review before the interview

Common mistakes

  • Running it on an unsorted array, which can give wrong answers without any error.
  • Setting low = mid or high = mid in this version, which can loop forever.
  • Writing while (low < high), which skips the last remaining element.
  • Using (low + high) / 2, which can overflow for very large indexes.

Edge cases to test

  • Empty array returns -1.
  • One element, both found and not found.
  • Target smaller than the first or larger than the last element.
  • Duplicates: the basic version can return any matching index.

Interview follow-ups

  • How do you find the last index of a repeated value?
  • How do you find the position where a missing value should be inserted?
  • How would you search a sorted array that has been rotated?

Keep practising

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us