Searchin Rotated Sorted Array Algorithm

The Search in Rotated Sorted Array Algorithm is an efficient search algorithm that aims to find a target value in a sorted array that has been rotated at some unknown pivot. The rotated sorted array means that the array is originally sorted in ascending order, but it has been rotated by some number of elements, moving the smallest element to a different position. This algorithm is particularly useful in scenarios where we have a large dataset of sorted numbers that has been disrupted by a rotation, and we need to quickly search for a specific value within that dataset. The algorithm is based on a modified version of binary search, which is an efficient search algorithm that works on sorted arrays by repeatedly dividing the search interval in half. The key difference is that with the rotated sorted array, we cannot guarantee that the middle element is greater than or less than the target value. To handle this case, we first identify which half of the array is sorted, either the left half or right half. If the target value lies within the sorted half, we can perform a regular binary search on that half. If the target value is not within the sorted half, we can discard that half and repeat the process on the other half. By iteratively narrowing down the search space, we can efficiently locate the target value with a time complexity of O(log n), where n is the number of elements in the array.
class Solution {
public:
    int search(int A[], int n, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        int lf = 0, rt = n - 1;
        while (lf <= rt) {
            int m = lf + (rt - lf) / 2;
            if (A[m] == target)
                return m;
            
            if (A[lf] <= A[m]) {
                if (A[lf] <= target && target < A[m])
                    rt = m - 1;
                else
                    lf = m + 1;
            }
            else {
                if (A[m] < target && target <= A[rt])
                    lf = m + 1;
                else
                    rt = m - 1;
            }
        }
        return -1;
    }
};

LANGUAGE:

DARK MODE: