Python Program for Binary Search Using Recursion
Intermediate · Recursion
Binary search finds a value in a sorted list by looking at the middle item and then searching only the half that could still contain it. Searching that half is the same problem on a smaller list, so binary search fits recursion naturally. This program prints each step and handles a value that is not in the list.
Program
Looking for 58 Searching indexes 0 to 9, middle value 34 Searching indexes 5 to 9, middle value 63 Searching indexes 5 to 6, middle value 46 Searching indexes 6 to 6, middle value 58 58 found at index 6 Looking for 30 Searching indexes 0 to 9, middle value 34 Searching indexes 0 to 3, middle value 12 Searching indexes 2 to 3, middle value 19 Searching indexes 3 to 3, middle value 27 30 is not in the list
How it works
lowandhighare the first and last index of the part of the list still being searched, and the first call passes the whole list, 0 tolen(numbers) - 1.- There are two base cases:
low > highmeans nothing is left to search, so the function returns -1, and finding the target atmidreturns its index. - Otherwise the recursive step searches one half,
lowtomid - 1when the target is smaller than the middle value, ormid + 1tohighwhen it is bigger. - Each call halves the range, so even a list of 1,000 items needs at most about 10 calls.
- The list must be sorted, or throwing away half of it could throw away the target.
Other ways to write it
With default arguments
Index of 71: 8 Index of 5: 0 Index of 100: -1 (not found)
Default values for low and high let the caller write just binary_search(numbers, 71), and the function fills in the whole range on the first call.
Using slicing
27 in the list: True 50 in the list: False
Passing a slice is simpler to read, but each slice is a copy and its positions do not match the original list, so this version only says whether the value is there.
Try it yourself
Add a calls parameter that goes up by 1 on each call, and print how many calls it takes to find 88 and to give up on 100.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises