Advertisement
gruntfutuk

binarychop

Feb 22nd, 2019
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.03 KB | None | 0 0
  1. 'Example binary chop search'
  2.  
  3. def search(source, matching):
  4.     'search container <source> to find position of <matching>'
  5.     'return 0 for not found or position where found starting from 1'
  6.     lower = 0
  7.     upper = len(source) - 1
  8.     while lower <= upper:  # note the addition of the = sign
  9.         middle = (lower + upper) // 2
  10.         if source[middle] == matching:
  11.             return middle + 1  # human's count from 1
  12.         else:
  13.             if source[middle] < matching:
  14.                 lower = middle + 1
  15.             else:
  16.                 upper = middle - 1
  17.     return 0
  18.  
  19.  
  20. original = [120,158,78,52,1859,2000,15,14,22,24,56]
  21. tests = original[:]
  22. tests.insert(3, 999)  #  number not in list, to check not found works
  23.  
  24. original.sort()
  25. print('Sorted lists of numbers: ', end='')
  26. print(*original, sep=", ")
  27. print()
  28.  
  29. for target in tests:
  30.     pos = search(original, target)
  31.     if pos:  # 0 == False, not 0 == True
  32.         print (f"{target:4} found at position {pos:3}")
  33.     else:
  34.         print(f"{target:4} not found")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement