Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def binary_search(lst, num):
- """
- A Binary Searching Method that can be used under the condition that the list is sorted
- :param lst: A sorted list or tuple
- :param num: The number we're searching for
- :return: Boolean: If we found the number in the list or not
- """
- # Define all the points I plan on using
- start = 0
- end = len(lst) - 1
- mid = end // 2
- # Our Sentinel value for if we found our value
- found = False
- while start <= end and not found:
- # Is the number we're looking for is at our midpoint
- if lst[mid] == num:
- found = True
- # Is the number greater than the point we're looking at
- elif num > lst[mid]:
- start = mid + 1
- mid = (start + end) // 2
- # Is the number lesser than the point we're looking at
- elif num < lst[mid]:
- end = mid - 1
- mid = (start + end) // 2
- return found
- from random import randint
- l = [i for i in range(1000)]
- n = randint(0, 1000)
- print(binary_search(l, n))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement