Binary search

Find the Target Element in a Sorted Array

Estimated reading: 1 minute 39 views

Problem:

Given a sorted array nums of n integers and a target value, return the index of the target if it is found in the array. If it is not found, return -1.

				
					public int binarySearch(int[] nums, int target) {
    int left = 0;
    int right = nums.length - 1;
    
    while (left <= right) {
        int mid = left + (right - left) / 2; // Calculate mid to avoid overflow
        
        if (nums[mid] == target) {
            return mid; // Target found
        } else if (nums[mid] < target) {
            left = mid + 1; // Search in the right half
        } else {
            right = mid - 1; // Search in the left half
        }
    }
    
    return -1; // Target not found
}

				
			
Share this Doc

Find the Target Element in a Sorted Array

Or copy link

CONTENTS