Following 2 algorithms both have O(n) complexity, however the second one using recursion runs much much slower than the first approach which uses a "for loop". Is it because recursion is expensive in Python? In the recursion method I assume O(n) because there are n/2 + n/4 + n/8 ... = n comparisons performed in total. I would appreciate if someone could shed more light on how recursion in Python works.
def findmax1(array):
curr = array[0]
for i in range(1,len(array)):
if array[i] > curr:
curr = array[i]
return curr
def findmax2_aux(left, right):
if left > right:
return left
else:
return right
def findmax2(array):
if len(array) <= 1:
return array
mid = len(array)//2
left, right = array[:mid], array[mid:]
left = findmax2(left)
right = findmax2(right)
return findmax2_aux(left, right)
from random import randint
test_array = [randint(1,1000) for x in range(1000000)]
t1 = time.time()
findmax1(test_array)
print(time.time()-t1)
# 0.08
t2 = time.time()
findmax2(test_array)
print(time.time()-t2)
# 1.05