Last active
October 20, 2021 16:16
-
-
Save ssshukla26/a8c84d6a6e2af77c00c613810f935e47 to your computer and use it in GitHub Desktop.
Find Pivot in a sorted but shifted/rotated array in O(log n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Find pivot in a sorted but shifted/rotated array using binary search | |
def pivot(arr, low, high): | |
if low <= high: | |
# Calc Mid | |
mid = low + (high-low)//2 | |
# Base Case: monotonic sequence e.g. [0,1,2,3] | |
if arr[low] < arr[high]: | |
return low | |
# descreasing sequence to right, throw away mid | |
# as we need to find the lowest possible value | |
# which is towards right | |
elif arr[mid] > arr[high]: | |
return pivot(arr, mid+1, high) | |
# increasing sequence to left and don't throw away mid | |
# as it can be the lowest possible value while going left | |
elif arr[mid] < arr[low]: | |
return pivot(arr, low, mid) | |
# Do Nothing | |
else: | |
pass | |
return low # default | |
p = [0,1,2,4,5,6,7] | |
x = [4,5,6,7,0,1,2] | |
y = [2,4,5,6,7,0,1] | |
z = [1,2,4,5,6,7,0] | |
w = [5,6,7,0,1,2,4] | |
q = [6,7,0,1,2,4,5] | |
print(pivot(p, 0, len(p)-1), p) | |
print(pivot(x, 0, len(x)-1), x) | |
print(pivot(y, 0, len(y)-1), y) | |
print(pivot(z, 0, len(z)-1), z) | |
print(pivot(w, 0, len(w)-1), w) | |
print(pivot(q, 0, len(q)-1), q) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment