'''lecture_37_recursion_binary_search.py Performs the binary search algorithm using recursion Oliver W. Layton CS 151: Computational Thinking: Visual Media Fall 2020 ''' def binarySearch(theList, elem, leftIdx, rightIdx): '''Binary search algorithm, done recursively Parameters: ----------- theList: the original list of numbers to search elem: the number we're looking for leftIdx: index of the left side of the "sublist range" we're searching in rightIdx: index of the right side the "sublist range" we're searching in Returns: ----------- int. Index of `elem` in `theList`. If `elem` is not in `theList`, return -1. ''' if leftIdx > rightIdx: # No way elem is in here! return -1 mid = (leftIdx + rightIdx) // 2 midItem = theList[mid] if midItem == elem: # We're good! Here it is! Return its index in the list return mid elif elem < midItem: # Repeat search in left half of list return binarySearch(theList, elem, leftIdx, mid-1) else: # Repeat search in right half of list return binarySearch(theList, elem, mid+1, rightIdx) if __name__ == '__main__': myList = [1, 2, 8, 9, 11, 20] left = 0 right = len(myList) - 1 print(binarySearch(myList, 11, left, right)) # 4 # print(binarySearch(myList, 2, left, right)) # 1 # print(binarySearch(myList, 7, left, right)) # -1