finding maximum element of a list - divide and conquer approach

Here I share my Python implementation of divide and conquer approach of finding maximum element from a list :
"""
Divide and conquer approach to find the maximum from a list
"""

def find_max(li, left, right):
    if left == right:
        return li[left]
    mid = (left + right) / 2
    max1 = find_max(li, left, mid)
    max2 = find_max(li, mid+1, right)
    return max1 if max1 > max2 else max2
    
    
def main():
    li = [1, 5, 2, 9, 3, 7, 5, 2, 10]
    print "Maximum element of the list is", find_max(li, 0, len(li)-1)
    
    
if __name__ == "__main__":
    main()

Comments

PiaFraus said…
Hi,
I've just subscribed to this blog, so I might missing something here.
But could you please explain the reasoning for this?
Even for this example with small amount of elements, this approach will have 17 function calls, with storing all the locals and also it will have 25 comparisons. Why is it better that something simple like
max = li[0]
for el in li:
if el > max:
max = el
?
Tamim Shahriar said…
Your simple solution is better than the one I have wrote. In fact I won't use my solution for any production code. But the importance of my solution is for the divide and conquer technique. It is a simple and beautiful example of divide and conquer (and recursion of course). Somebody in a facebook group asked how many different ways we can find the maximum from a list, so I posted this solution. :)
Grant said…
It's also worth noting that Python has a built-in `max` function (https://docs.python.org/2/library/functions.html#max) that will be considerably faster and simpler than the other approaches described here.
I do believe this is a direct implementation for the pseudo code for finding max element in a list.
Work appreciated, but I do believe doesn't worth to be blogged.
you might consider some complex algorithms like those using dynamic programming and maybe graph algorithms to implement in python. I might suggest the "longest common sub-sequence" and "shortest path in directed graphs".

Appreciate your efforts :)
Unknown said…
I tried this code but it is creating a deep recursion.The reason for it is that the line-
mid = (left + right) / 2
is not resulting in a integer value. Instead, you can use-
mid = int((left + right) / 2)

P.S.- I am using python 3.5
chuanbing said…
li = [1, 5, 2, 9, 3, 7, 5, 2, 10]
reduce(lambda x,y : x if x > y else y ,li)
Amaro Vita said…
It's not any faster than linear search...
Tamim Shahriar said…
Right, it's just to demonstrate divide and conquer technique.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code