Search in Rotated Sorted Array in Python

Consider we have an array sorted in ascending order, and that is rotated at some pivot unknown to you beforehand. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. We have given a target value to the search. If we can get it in the array, then return its index, otherwise return -1. We can assume no duplicate exists in the array. So if the array is like [4,5,6,7,0,1,2], then the output will be 4. as the index of this element is present at index 4.

To solve this, we will follow these steps −

• low := 0 and high := length of array
• while low < high
• find mid as mid := low + (high - low)/2
• if arr[mid] = target, then return mid
• if arr[low] <= arr[mid]
• if target >= arr[low] and target < arr[mid], then high := mid, otherwise low := mid + 1
• otherwise
• if target <= arr[high - 1] and target > arr[mid], then low := mid + 1, otherwise high := mid
• return -1

Example(Python)

Let us see the following implementation to get better understanding −

Live Demo

class Solution(object):
def search(self, nums, target):
low = 0
high = len(nums)
while low<high:
mid = low + (high-low)//2
if nums[mid] == target:
return mid
if nums[low]<=nums[mid]:
if target >=nums[low] and target <nums[mid]:
high = mid
else:
low = mid+1
else:
if target<=nums[high-1] and target>nums[mid]:
low = mid+1
else:
high = mid
return -1
ob1 = Solution()
print(ob1.search([4,5,6,7,8,0,1,2], 0))

Input

[4,5,6,7,0,1,2]
0

Output

5