Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def local_maxima(A, ind_left, ind_right):
- # check the edge cases
- if ind_left == 0 and A[ind_left] >= A[ind_left + 1]:
- return ind_left
- elif ind_right == len(A) - 1 and A[ind_right - 1] <= A[ind_right]:
- return ind_right
- ind_mid = (ind_left + ind_right) // 2
- # case 0:
- if A[ind_mid - 1] <= A[ind_mid] >= A[ind_mid + 1]:
- return ind_mid
- # case: 1
- elif A[ind_mid] < A[ind_mid + 1]:
- return local_maxima(A, ind_mid + 1, ind_right)
- # case: 2
- else:
- return local_maxima(A, ind_left, ind_mid - 1)
- def main():
- arr = [1, 10, 9, 8, 7]
- assert len(arr) >= 2, "please use an array with length >= 3"
- # Note that the below sorted check is done for validity of question
- # and this logic is not actually part of the solution
- is_ascending = True
- is_descending = True
- for i in range(len(arr) - 1):
- if arr[i] > arr[i + 1]:
- is_ascending = False
- elif arr[i] < arr[i + 1]:
- is_descending = False
- is_sorted = is_ascending or is_descending
- assert is_sorted is False, "please use an unsorted array"
- print(local_maxima(arr, 0, len(arr) - 1))
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement