Advertisement
Ikem

helpers.py

Feb 14th, 2018
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.92 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- encoding: utf-8 -*-
  3.  
  4. def search(value, values):
  5.     start = 0
  6.     end = len(values) - 1
  7.  
  8.     result = bsearch(value, values, start, end)
  9.    
  10.     print("Number found: {}".format(result))
  11.  
  12. def bsearch(value, values, start, end):
  13.     print("Search {} in {}...".format(value, values[start:end+1]))
  14.  
  15.     middle = (start + end) // 2
  16.  
  17.     current_value = values[middle]
  18.    
  19.     if current_value == value:
  20.         return True
  21.     elif current_value != value and start == end:
  22.         return False
  23.     elif current_value > value:
  24.         print("Search left...")
  25.        
  26.         return bsearch(value, values, start, middle - 1)
  27.     else:
  28.         print("Search right...")
  29.        
  30.         return bsearch(value, values, middle + 1, end)
  31.  
  32. values = [1, 3, 6, 9, 10, 14, 16, 17, 21]
  33.  
  34. print("Testing the algorithm...")
  35.  
  36. for value in values:
  37.     search(value, values)
  38.  
  39. search(7, values)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement