Programming & Development / April 18, 2025

Binary Search in Java – A Simple Example

Binary Search Java Algorithm Search Array Data Structures Java Interview Prep

Binary Search is one of the most efficient searching algorithms used on sorted arrays. It works by repeatedly dividing the search interval in half, reducing the time complexity to O(log n). In this article, we’ll walk through a clean implementation of binary search in Java with a practical example.

🧠 How Binary Search Works

The algorithm compares the target value to the middle element of the array:

  • If they match, it returns the index.
  • If the target is smaller, search the left half.
  • If the target is larger, search the right half.
  • Repeat until the value is found or the range becomes invalid.

🧾 Java Code Example

java

public class BinarySearch {

    // Binary search function
    public static int binarySearch(int[] array, int key) {
        int low = 0;
        int high = array.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2; // Safe midpoint to avoid overflow

            if (array[mid] == key) {
                return mid; // Key found
            } else if (array[mid] < key) {
                low = mid + 1; // Search in right half
            } else {
                high = mid - 1; // Search in left half
            }
        }

        return -1; // Key not found
    }

    public static void main(String[] args) {
        int[] sortedArray = {2, 3, 4, 10, 40};
        int key = 10;

        int result = binarySearch(sortedArray, key);

        if (result == -1) {
            System.out.println("Element not present in array");
        } else {
            System.out.println("Element found at index " + result);
        }
    }
}

πŸ” Explanation

  • Function: binarySearch(int[] array, int key)
  • Input: Sorted integer array and the value to search.
  • Output: Index of the value in the array, or -1 if not found.

πŸ”‘ Key Variables:

VariableMeaninglowStart of search rangehighEnd of search rangemidMiddle of the current range

βœ… Example Output

pgsql

Element found at index 3

The key 10 is found at index 3 in the array {2, 3, 4, 10, 40}.

πŸ“Œ Summary

  • 🧭 Binary Search is optimal for sorted arrays.
  • ⚑ Time Complexity: O(log n)
  • πŸ” Works by halving the search range until the target is found or not present.

This is a core concept in many coding interviews, especially for roles that focus on problem-solving and algorithmic thinking. If you’re preparing for interviews, make sure you’re also familiar with recursive implementations and how binary search applies to real-world problems like finding boundaries, ranges, and more.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex