Search in Rotated Sorted Array in TypeScript

function search(nums: number[], target: number): number {
    // Initialize the left and right pointers. 
    // 'left' starts from the beginning of the array, and 'right' starts from the end.
    let left = 0;
    let right = nums.length - 1;

    // The while loop continues as long as 'left' does not surpass 'right'.
    // This ensures that the search space is valid.
    while (left <= right) {
        // Calculate the middle index of the current search space.
        // This is done by averaging 'left' and 'right', effectively dividing the search space in half.
        let mid = Math.floor((left + right) / 2);

        // Check if the middle element is the target. If so, return its index.
        if (nums[mid] === target) {
            return mid;
        }

        // Determine if the left half of the array is sorted.
        // A sorted half will have its start less than or equal to its middle.
        if (nums[left] <= nums[mid]) {
            // If the target is within the range of the sorted left half,
            // discard the right half by moving 'right' just before 'mid'.
            if (target >= nums[left] && target < nums[mid]) {
                right = mid - 1;
            } 
            // Otherwise, discard the left half by moving 'left' just after 'mid'.
            else {
                left = mid + 1;
            }
        } 
        // If the left half is not sorted, then the right half must be sorted.
        else {
            // If the target is within the range of the sorted right half,
            // discard the left half by moving 'left' just after 'mid'.
            if (target > nums[mid] && target <= nums[right]) {
                left = mid + 1;
            } 
            // Otherwise, discard the right half by moving 'right' just before 'mid'.
            else {
                right = mid - 1;
            }
        }
    }

    // If the target is not found in the array, return -1.
    return -1;
}

PrevNext