I want to find the maximum element in an array in O(log N)
time using divide and conquer. I found a working code at planet-source-code. I translated it into Python as follows:
def largest(arr,i,j):
global max1
global max2
if i == j:
max1 = arr[i]
else:
if i == j-1:
max1 = arr[i] if arr[i] > arr[j] else arr[j]
else:
mid = (i+j)/2
largest(arr,i,mid)
max2 = max1
largest(arr,mid+1,j)
if max2 > max1:
max1 = max2
When I use an array [98,5,4,3,2,76,78,92]
, and call the code as
max1 = arr[0]
largest(arr,1,8)
I am getting a out-of-bound list index error. However the C code returns the correct result 98. Can anyone spot what error am I doing?