-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathfinal_broken_search.py
43 lines (37 loc) · 1.49 KB
/
final_broken_search.py
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
37
38
39
40
41
42
43
"""ID посылки: 88287031."""
def broken_search(nums: list[int], target: int) -> int:
"""Binary search for value in a shifted sorted list.
In order to choose which half to move to we need to know
the position of the shift. The shift can be located based
on the values of the left element (a), the middle (m)
and the target (t).
There are six possible arrangements of these three elements,
and for each arrangement their relative positions are enough
to make the choice.
On the diagram of arrangements below the shift is marked as |:
a--------t--m-----|----- a <= t <= m (choose left half)
a-----------m--t--|----- a <= m <= t (choose right half)
a-----------m-----|--t-- t <= a <= m (choose right half)
a--t--|-----m----------- m <= a <= t (choose left half)
a-----|--t--m----------- t <= m <= a (choose left half)
a-----|-----m--t-------- m <= t <= a (choose right half)
"""
left, right = 0, len(nums)
while left < right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if (
nums[mid] <= nums[left] <= target
or target <= nums[mid] <= nums[left]
or nums[left] <= target <= nums[mid]
):
right = mid
else:
left = mid + 1
return -1
if __name__ == '__main__':
_ = int(input())
target = int(input())
nums = [int(s) for s in input().split()]
print(broken_search(nums, target))