BudiBadu Logo

Binary Search Target Index

Binary Search Easy 4 views
Like9

Given a sorted array of integers in ascending order and a target value, write a function to find the index of the target value in the array using binary search. If the target is not present in the array, return -1.

Problem Details: The input array is guaranteed to be sorted in ascending order with no duplicate elements. Your task is to implement a binary search algorithm to locate the target value efficiently. Binary search works by repeatedly dividing the search interval in half. If the target value is found, return its index; otherwise, return -1. The solution should handle edge cases, such as an empty array or a target value not present in the array.

Example 1:

Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: The target value 9 is found at index 4 in the array.

Example 2:

Input: nums = [-1,0,3,5,9,12], target = 2
Output: -1
Explanation: The target value 2 is not present in the array, so return -1.

Example 3:

Input: nums = [], target = 5
Output: -1
Explanation: The array is empty, so return -1.

Algorithm Flow

Recommendation Algorithm Flow for Binary Search Target Index - Budibadu
Recommendation Algorithm Flow for Binary Search Target Index - Budibadu

Best Answers

java
class Solution {
    public int search(Object nums, Object target) {
        int[] arr = (int[]) nums;
        int t = (int) target;
        int left = 0;
        int right = arr.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == t) {
                return mid;
            } else if (arr[mid] < t) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }
}