Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from math import log2
- from random import randrange
- # Function 1
- def generateArray(length, LIMIT):
- array = list()
- for i in range(length):
- array.append(randrange(LIMIT))
- return array
- # Function 2
- def binarySearch(array, number):
- array = sorted(array)
- print("Sorted = " + str(array))
- N = len(array)
- searchesInitial = int(log2(N)) + 1
- maxSearches = searchesInitial
- found = False
- while maxSearches > 0:
- print(array)
- # 1) In case of a big array
- if len(array) >= 2:
- half = int(len(array)/2)
- if number > array[half]:
- array = array[half:len(array)]
- maxSearches -= 1
- print(">")
- elif number < array[half]:
- array = array[0:half]
- maxSearches -= 1
- print("<")
- else:
- found = True
- print("We found our number " + str(number) + " after " + str(searchesInitial - maxSearches + 1) + " tries")
- print("=")
- break
- # 2) In case of a one-element array
- elif len(array) == 1:
- if number == array[0]:
- print("We found our number " + str(number) + " after " + str(searchesInitial - maxSearches + 1) + " tries")
- else:
- print("!=")
- break
- if found == False:
- print("Your number " + str(number) + " is not located anywhere in our list...")
- # MAIN FUNCTION
- print()
- length = 10
- LIMIT = 10
- number = 5
- array = generateArray(length, LIMIT)
- print("Array = " + str(array))
- binarySearch(array, number)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement