Python Tricks #14 - Binary search is faster than linear

in #programming7 years ago (edited)
# Given list B = [2,5,7,8,9,11,14,16] find if 14 is present in this list or not.

def binarySearch(ls,data):
   first = 0
   last = len(ls)-1 

    while first<=last:
       mid = (first+last)//2
          if ls[mid] == data:
           return True
       else:
           if ls[mid] > data:
               last = mid-1
           else:
               first = mid+1
   return False 

print(binarySearch([2,5,7,8,9,11,14,16],4))

# Round First Last Mid ls[mid] Result
#     1     0   7   3   8         8<14
#     2     4   7   5   11        11<14
#     3     6   7   6   14       14=14

"""
NOTE: To find the mid element, “(first+last)//2” is used instead of “(first+last)/2”. This gives us whole
 numbers especially when the length of the list is odd. Try 9/2 and 9//2 in your Python IDLE to get a 
better understanding.

From the above explanation, it must be clear that Binary Search is consistently faster than Linear Search. 
If you are familiar with o(n) notation, Linear Search is o(n) and Binary Search is log(n)

You can perform Linear Searches on a sorted list as well with a small optimization. You can stop the 
search once the number to be found exceeds the element being compared to. For instance, you want to 
search for 12 from the list [2,4,5,13,16,19], once you reach 13 you can stop because there is no way that 
12 is going to come after 13 in a sorted list.
"""
Sort:  

You could make it even a little faster by using the return True statement instead of done = True and remove done from the program by writing return False at the end. That way you don't need to test and not done every loop.

Also I think you meant to use last = mid-1 and
first = mid+1. Otherwise your program would be linear.

Thanks for your notes! Indeed it is more pytonic without done variable. I made corrections according to your suggestions. Thanks!

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.083
BTC 60791.27
ETH 1560.80
USDT 1.00
SBD 0.47