i know there are lots of solution to find the maximum in a sorted rotated array. But below is my code and i want to modify these code to work on all the input. Right now on few cases, its not working.
Help me to find the bug. if any modifications are required, then let me know.
#arr is the list of elements
#length is the length of the list
#left,right and mid indicates the different positions of the array
def find_max(arr,length):
left=0
right=length-1
while left<right :
if right-left==1 :
return max(arr[left],arr[right])
mid=(left+right)>>1
if arr[mid]>arr[right]:
left=mid
else:
right=mid-1
return arr[left]
This code fails for below output : arr=[5, 6, 7, 1, 2, 3, 4]
For this output is 5 while it should be 7.
i found the answer finally with the help of Trincot.Here i am posting the answer for anyone who will look for it in future.
def find_max(arr,length):
left=0
right=length-1
while left<right :
if arr[left] < arr[right]:
return arr[right]
mid=(left+right)>>1
if arr[mid]>arr[right]:
left=mid
else:
right=mid-1
return arr[left]
:)