Skip to content Skip to sidebar Skip to footer

Optimize Binary Search

I am new to python, and very much enthusiastic to learn algorithm. I have written sample code for Binary search, can any one suggest how can i achieve same result in more pythonic

Solution 1:

Probably this answers part of your question. You don't really need to get the middle index, you can compare the maximum value in alist with target:

defbee_search(alist, target):
    largest = max(alist)
    if target == largest: 
        print"Found", target
    elif target < largest: 
        print"Found", target
    else:                  # target > largestprint("Not found")

This is okay when target == largest and when target > largest but not when target < largest, yes this is a broken algorithm!

arr = [1,0,2,3, 10, 200, 5, 29, 10, 39, 109]
bee_search(arr, 30)

When run this is the output:Found 30.

This problem applies to your algorithm too, a simple comparison cannot tell us definitely whether alist has a reference for integer 30. You may need to consider workarounds, don't give up.

Post a Comment for "Optimize Binary Search"