elena_gancedo

Simple_Binary_search_2

Sep 12th, 2019
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. print ("*****************************************************************************************************")
  2. # Binary search in Python list using recursion
  3. # The user creates the list by entering the numbers
  4. vector = []
  5. num = int(input('How many items in the list?: '))
  6. for n in range(num):
  7.     number = int(input("Enter a number in the list: "))
  8.     vector.append(number)
  9. #This is the vector that the algorithm will use to find any data    
  10. print ("Let's look in the following list:", vector)
  11. #The "search" variable will be the start of the vector, which is 0
  12. search = 0
  13. #We ask the user for an integer entry
  14. number = float (input ("Enter the data you want to find:"))
  15. def binary_recursive_search (vector, number, left, right):
  16.     if left > right:
  17.         return -1
  18.     IndexMiddleItem = (left + right) // 2
  19.     middle_item = vector [IndexMiddleItem]
  20.     if  middle_item == number:
  21.         return IndexMiddleItem
  22.     if number < middle_item:
  23.         return  binary_recursive_search (vector, number, left, IndexMiddleItem - 1)
  24.     else:  
  25.         return  binary_recursive_search (vector, number, IndexMiddleItem + 1, right)
  26. #The index is equal to the "vector" list, the number of the list, the length of the list.
  27. index = binary_recursive_search (vector, number, 0, len (vector) - 1)
  28. print ("The data {} is in the index {}". format (number, index+1))
  29. print ("*****************************************************************************************************"
Add Comment
Please, Sign In to add comment