Start learning free

LESSON 268 OF 410 · BINARY SEARCH

Binary Search in Java

Lesson O(log n) Read the full explanation

In this video lesson we will learn about the concept of searching, linear searching and more important - Binary Searching:


Problem:

Given a sorted array of integers nums, use Binary Search to find and return the index of a given value.

If the value doesn't exist in nums, return -1.


Example 1:

Input: nums = [1, 2, 4, 5], value = 4
Output: 2
Explanation: the element at index 2 is 4

Note:

Your algorithm should run in O(log n) time and use O(1) extra space.


STEP 1 OF 7
    Ctrl + Enter to check

    JAVA · BINARY SEARCH

    Binary Search in Java, explained

    Introduction

    Binary Search is a fundamental algorithm in computer science used to find the position of a target value within a sorted array. It is significantly more efficient than linear search, especially for large datasets, as it reduces the search space by half with each step. This makes it particularly useful in scenarios where quick search times are critical, such as in databases, search engines, and real-time systems.

    Understanding the Basics

    Binary Search works on the principle of divide and conquer. The algorithm repeatedly divides the search interval in half. If the value of the search key is less than the item in the middle of the interval, the algorithm narrows the interval to the lower half. Otherwise, it narrows it to the upper half. This process continues until the value is found or the interval is empty.

    For example, consider the sorted array [1, 2, 4, 5] and the target value 4. The algorithm will start by comparing 4 with the middle element 2. Since 4 is greater than 2, it will then compare 4 with the middle element of the upper half, which is 4. The target value is found at index 2.

    Main Concepts

    The key concepts in Binary Search include:

    • Midpoint Calculation: Calculate the middle index of the current search interval.
    • Comparison: Compare the target value with the middle element.
    • Interval Adjustment: Adjust the search interval based on the comparison result.

    Here is the logical flow of the Binary Search algorithm:

    1. Initialize two pointers, left and right, to the start and end of the array, respectively.
    2. While left is less than or equal to right:
      • Calculate the midpoint mid.
      • If nums[mid] equals the target value, return mid.
      • If nums[mid] is less than the target value, move the left pointer to mid + 1.
      • If nums[mid] is greater than the target value, move the right pointer to mid - 1.
    3. If the target value is not found, return -1.

    Examples and Use Cases

    Let's look at a few examples to understand how Binary Search works in different scenarios:

    Example 1:
    Input: nums = [1, 2, 4, 5], value = 4
    Output: 2
    Explanation: nums[2] is 4
    
    Example 2:
    Input: nums = [1, 2, 4, 5], value = 3
    Output: -1
    Explanation: 3 is not in the array
    
    Example 3:
    Input: nums = [1, 2, 4, 5, 6, 7, 8], value = 6
    Output: 4
    Explanation: nums[4] is 6
    

    Common Pitfalls and Best Practices

    Common mistakes to avoid when implementing Binary Search include:

    • Incorrect midpoint calculation, which can lead to infinite loops or incorrect results.
    • Not updating the search interval correctly, causing the algorithm to miss the target value.

    Best practices for writing efficient and maintainable Binary Search code include:

    • Ensure the array is sorted before performing Binary Search.
    • Use integer division to calculate the midpoint to avoid overflow issues.
    • Write clear and concise code with appropriate comments.

    Advanced Techniques

    Advanced techniques related to Binary Search include:

    • Binary Search on a rotated sorted array: This involves modifying the standard Binary Search algorithm to handle arrays that have been rotated.
    • Finding the first or last occurrence of a target value: This requires slight modifications to the standard Binary Search to ensure the correct index is returned.

    These techniques are useful in more complex scenarios where the standard Binary Search algorithm needs to be adapted to specific requirements.

    Code Implementation

    Here is a Java implementation of the Binary Search algorithm:

    public class BinarySearch {
        // Function to perform binary search on a sorted array
        public static int binarySearch(int[] nums, int value) {
            int left = 0; // Initialize left pointer
            int right = nums.length - 1; // Initialize right pointer
    
            // Loop until the search interval is valid
            while (left <= right) {
                int mid = left + (right - left) / 2; // Calculate the midpoint
    
                // Check if the middle element is the target value
                if (nums[mid] == value) {
                    return mid; // Return the index if found
                }
    
                // If the target value is greater, ignore the left half
                if (nums[mid] < value) {
                    left = mid + 1;
                } else {
                    // If the target value is smaller, ignore the right half
                    right = mid - 1;
                }
            }
    
            // Return -1 if the target value is not found
            return -1;
        }
    
        // Main method to test the binary search function
        public static void main(String[] args) {
            int[] nums = {1, 2, 4, 5};
            int value = 4;
            int result = binarySearch(nums, value);
            System.out.println("Index of " + value + ": " + result); // Output: 2
        }
    }
    

    Debugging and Testing

    When debugging Binary Search code, consider the following tips:

    • Print the values of left, right, and mid at each step to trace the algorithm's execution.
    • Check edge cases, such as an empty array or an array with a single element.

    To test the Binary Search function, write test cases that cover various scenarios, including:

    • Target value present in the array.
    • Target value not present in the array.
    • Array with duplicate elements.
    • Array with negative numbers.

    Thinking and Problem-Solving Tips

    When approaching problems related to Binary Search, consider the following strategies:

    • Understand the problem requirements and constraints.
    • Break down the problem into smaller steps and solve each step incrementally.
    • Practice implementing Binary Search on different types of problems to build familiarity and confidence.

    Conclusion

    Binary Search is a powerful algorithm that offers efficient search capabilities for sorted arrays. By mastering Binary Search, you can significantly improve the performance of your programs and solve a wide range of problems more effectively. Practice implementing and applying Binary Search to various scenarios to deepen your understanding and enhance your problem-solving skills.

    Additional Resources

    For further reading and practice problems related to Binary Search, consider the following resources:

    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free