Sunday, January 12, 2014

Searching number in sorted but rotated array


Consider a sorted array as below 

15  19  29  34  35  49   96  97 99

the rotated sorted array of this array can be 

49 96  97 99  15  19  29  34  35  

Approach 1:
We have to find the element from this array. With linear search we can find the element in o(n) time complexity. But as array is sorted we should take advantage of this property.
Approach 2:
We can use the binary search for searching the PIVOT element. Pivot element will denote the starting point of rotation.  You can check the Binary search is implementation here.
With this we will minimize the search area and then apply the binary search again on the remaining array.

Approach 3:
With above approach we will be doing two pass of binary search one for searching pivot and one for searching the number. We can even think of modifying the binary search as we know if the array is rotate. 
Code below shows how we can use modified binary search method to find element in sorted but rotated array.
   

//Num is number to search

int SearchNum(vector<int> & input, int start, int end, const int num)
{
    if (start <= end)
    {
        int mid = start + (end - start) / 2;
        if (num == input[mid])
            return mid;
        if (input[mid] < input[end])
        {
            if (input[mid] < num && input[end] >= num)
                return SearchNum(input, mid + 1, end, num);
            else
                return SearchNum(input, start, mid - 1, num);
        }
        else
        {
            if (input[start] <= num && input[mid] > num)
                return SearchNum(input, start, mid - 1, num);
            else
                return SearchNum(input, mid + 1, end, num);
        }
    }
    return -1;
}

The function will return -1 if it failed to find the number else it will return index of the number in the array.



No comments:

Post a Comment