Fork me on GitHub

Binary search in rotated array

Linkage

https://leetcode.com/problems/search-in-rotated-sorted-array/description/

Analysis

In this situation, we need another item for comparison when we determine which side to do further search. In my code, we set the first item of the array as the compliment to help us compare. To be more specific, the code show the two cases which composes of all the situation.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution:
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
lens = len(nums)
if lens == 0:
return -1
return self.find(nums, 0, lens-1, target)

def find(self, nums, left, right, target):

while left <= right:

middle = int ( (left + right) / 2 )
if nums[middle] == target:
return middle
if left == right and nums[middle] != target:
return -1

##Right sorted
if nums[middle] < nums[0]:
if target > nums[middle] and target < nums[0]:
left = middle + 1
else:
right = middle - 1
##Left is sorted
else:
if target < nums[middle] and target >= nums[0]:
right = middle - 1
else:
left = middle + 1

return -1