Find element in rotated sorted array

A sorted array of integers was rotated an unknown number of times.

Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't exist in the array, return null.

For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array).

You can assume all the integers in the array are unique.

Example:

Input:  arr = [13,18,25,2,8,10], target = 8
Output: 4

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int searchElement(vector<int&numsint target)
{
    int low = 0high = nums.size() - 1;

    //iterate till low is less than high
    while (low <= high)
    {

        //calculate mid point
        int mid = low + (high - low) / 2;

        //if target value is same as mid
        //value then return it
        if (nums[mid] == target)
            return mid;

        //if mid value is less than low value
        else if (nums[mid] < nums[low])
        {
            //if target is greater than mid and 
//target is less than
            //high than update low
            if (target > nums[mid] && target <= nums[high])
                low = mid + 1;

            //else update high
            else
                high = mid - 1;
        }

        //if mid value is greater than high
        else if (nums[mid] > nums[high])
        {

            //if target is less than mid and target is
// greater than
            //low then update high
            if (target < nums[mid] && target >= nums[low])
                high = mid - 1;

            //else update low
            else
                low = mid + 1;
        }
        else
        {
            //update high
            if (target < nums[mid])
                high = mid - 1;

            //else update low
            else
                low = mid + 1;
        }
    }
    return -1;
}

int main()
{
    vector<intnums = {1318252810};
    int target = 8;
    cout << searchElement(numstarget);
    return 0;
}


No comments:

Post a Comment