Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- print ("*****************************************************************************************************")
- # Binary search in Python list using recursion
- # The user creates the list by entering the numbers
- vector = []
- num = int(input('How many items in the list?: '))
- for n in range(num):
- number = int(input("Enter a number in the list: "))
- vector.append(number)
- #This is the vector that the algorithm will use to find any data
- print ("Let's look in the following list:", vector)
- #The "search" variable will be the start of the vector, which is 0
- search = 0
- #We ask the user for an integer entry
- number = float (input ("Enter the data you want to find:"))
- def binary_recursive_search (vector, number, left, right):
- if left > right:
- return -1
- IndexMiddleItem = (left + right) // 2
- middle_item = vector [IndexMiddleItem]
- if middle_item == number:
- return IndexMiddleItem
- if number < middle_item:
- return binary_recursive_search (vector, number, left, IndexMiddleItem - 1)
- else:
- return binary_recursive_search (vector, number, IndexMiddleItem + 1, right)
- #The index is equal to the "vector" list, the number of the list, the length of the list.
- index = binary_recursive_search (vector, number, 0, len (vector) - 1)
- print ("The data {} is in the index {}". format (number, index+1))
- print ("*****************************************************************************************************"
Add Comment
Please, Sign In to add comment