Binary Search

Binary Search

Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

You must write an algorithm with O(log n) runtime complexity.\

LeetCode Problem - 704: Link | Click Here

class Solution {
    // Method to perform binary search in a sorted array
    public int search(int[] nums, int target) {
        // Initialize the search range
        int low = 0;
        int high = nums.length - 1;

        // Binary search loop
        while (low <= high) {
            // Calculate the middle index of the current search range
            int mid = low + (high - low) / 2;

            // Check if the middle element is equal to the target
            if (nums[mid] == target) {
                return mid;  // Return the index if target is found
            } else if (nums[mid] > target) {
                high = mid - 1;  // Adjust the search range to the left half
            } else {
                low = mid + 1;   // Adjust the search range to the right half
            }
        }

        // Return -1 if the target is not found in the array
        return -1;
    }
}