It is to find the maximum element in an array which is first increasing and then decreasing. I've tried to write my idea by using divide and conquer approach. Is there any improvable or missing point? My code is following,
def search(arr, low, high):
if low == high:
return arr[low]
mid = low + (high - low) // 2
if arr[mid] > arr[mid + 1]:
# if it's peak that a number whose left and right are smaller than it, return it
if arr[mid] > arr[mid - 1]:
return arr[mid]
else:
return search(arr, low, mid)
else:
return search(arr, mid + 1, high)
if __name__ == "__main__":
arr = [ 70, 80, 9, 6 ]
arr2 = [60, 70, 72, 74, 88]
arr3 = [8, 10, 20, 80, 100, 200, 400, 500, 3, 2, 1]
arr4 = [10, 20, 30, 40, 50]
arr5 = [1, 3, 50, 10, 9, 7, 6]
arr6 = [120, 100, 80, 20, 0]
print(search(arr, 0, len(arr) - 1))
print(search(arr2, 0, len(arr2) - 1))
print(search(arr3, 0, len(arr3) - 1))
print(search(arr4, 0, len(arr4) - 1))
print(search(arr5, 0, len(arr5) - 1))
print(search(arr6, 0, len(arr6) - 1))
Output:
80
88
500
50
50
120