Advertisement
karlakmkj

Binary search sample with recursion

Jan 7th, 2021
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.39 KB | None | 0 0
  1. def binary_search(searchList, searchTerm):
  2.     #First, the list must be sorted.
  3.     searchList.sort()
  4. '''
  5. With each recursive call to binary_search, the size of the list will be cut in half, rounding down. If the search term is not found, then eventually an empty list will be passed into binary_search. So, if searchList is empty, we know that the search term was not found, and we can return False. This is the base case for the recursive binary_search.
  6. '''
  7.     if len(searchList) == 0:
  8.         print(searchTerm, "never found.")
  9.         return False
  10.  
  11.     #If there are still items in the list, then we want to find if searchTerm is greater than, less than, or equal to the middle term in the list. For that, we need the index of the middle term.
  12.     middle = len(searchList) // 2
  13.  
  14.     #First, the easy case: if it's the middle term, we found it! Return True.
  15.     if searchList[middle] == searchTerm:
  16.         print(searchTerm, "==", searchList[middle], "-- search term found!")
  17.         return True
  18.  
  19.     #If the search term is less than the middle term, then repeat the search on the left half of the list using recursion.
  20.     elif searchTerm < searchList[middle]:
  21.         print(searchTerm, "<", searchList[middle], "-- repeating for left side.")
  22.         return binary_search(searchList[:middle], searchTerm)
  23.  
  24.     #If the search term is greater than the middle term, then repeat the search on the right half of the list using recursion.
  25.     else:
  26.         print(searchTerm, ">", searchList[middle], "-- repeating for right side.")
  27.         return binary_search(searchList[middle + 1:], searchTerm)
  28. '''
  29. As long as there are items to be searched, binary_search will keep getting called on smaller and smaller lists, until eventually the item is found or the list of possible places it could be found is empty.
  30. '''
  31.  
  32. intlist = [12, 64, 23, 3, 57, 19, 1, 17, 51, 62]
  33. print("23 is in intlist:", binary_search(intlist, 23))
  34. print("50 is in intlist:", binary_search(intlist, 50))
  35.  
  36. strlist = ["David", "Joshua", "Marguerite", "Jackie"]
  37. print("David is in strlist:", binary_search(strlist, "David"))
  38. print("Lucy is in strlist:", binary_search(strlist, "Lucy"))
  39.  
  40. from datetime import date
  41. datelist = [date(1885, 10, 13), date(2014, 11, 29), date(2016, 11, 26)]
  42. print("10/13/1885 is in datelist:", binary_search(datelist, date(1885, 10, 13)))
  43. print("11/28/2015 is in datelist:", binary_search(datelist, date(2015, 11, 28)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement