Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Binary Search
- def binary_search(listnums,search):
- found = False
- left = 0
- right = len(listnums)-1
- while left!=right:
- midpoint = (left + right)//2
- if listnums[midpoint] == search:
- found = True
- break
- if search <= listnums[midpoint]:
- right = midpoint
- else:
- left = midpoint+1
- return found,midpoint
- import random
- listnums = []
- for i in range(0,50): #will populate 50 random numbers
- listnums.append(random.randint(0,100)) # will select 50 random numbers between 1-100)
- listnums.sort()
- print(listnums) #the numbers randomly selected will appear below
- print("what integer are you searching for between 1-100?")
- search = int(input()) #requires user to input a number
- found,midpoint = binary_search(listnums,search)
- print(found)
- print(midpoint+1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement