Advertisement
makispaiktis

Binary Search

Apr 25th, 2021 (edited)
965
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. from math import log2
  2. from random import randrange
  3.  
  4. # Function 1
  5. def generateArray(length, LIMIT):
  6.     array = list()
  7.     for i in range(length):
  8.         array.append(randrange(LIMIT))
  9.     return array
  10.  
  11. # Function 2
  12. def binarySearch(array, number):
  13.     array = sorted(array)
  14.     print("Sorted = " + str(array))
  15.     N = len(array)
  16.     searchesInitial = int(log2(N)) + 1
  17.     maxSearches = searchesInitial
  18.     found = False
  19.     while maxSearches > 0:
  20.         print(array)
  21.         # 1) In case of a big array
  22.         if len(array) >= 2:
  23.             half = int(len(array)/2)
  24.             if number > array[half]:
  25.                 array = array[half:len(array)]
  26.                 maxSearches -= 1
  27.                 print(">")
  28.             elif number < array[half]:
  29.                 array = array[0:half]
  30.                 maxSearches -= 1
  31.                 print("<")
  32.             else:
  33.                 found = True
  34.                 print("We found our number " + str(number) + " after " + str(searchesInitial - maxSearches + 1) + " tries")
  35.                 print("=")
  36.                 break
  37.         # 2) In case of a one-element array
  38.         elif len(array) == 1:
  39.             if number == array[0]:
  40.                 print("We found our number " + str(number) + " after " + str(searchesInitial - maxSearches + 1) + " tries")
  41.             else:
  42.                 print("!=")
  43.                 break
  44.  
  45.     if found == False:
  46.         print("Your number " + str(number) + " is not located anywhere in our list...")
  47.  
  48.  
  49. # MAIN FUNCTION
  50. print()
  51. length = 10
  52. LIMIT = 10
  53. number = 5
  54. array = generateArray(length, LIMIT)
  55. print("Array  = " + str(array))
  56. binarySearch(array, number)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement