Python Program for Binary Search
Intermediate · Searching and sorting
Binary search finds a value in a sorted list by checking the middle item and throwing away the half that cannot contain the target. Each step halves the part left to search, so even a list of a million numbers needs only about 20 checks. This program prints each step and reports when a number is not in the list.
Program
Searching for 42 in [3, 8, 15, 23, 42, 57, 71] Checking index 3, value 23 Checking index 5, value 57 Checking index 4, value 42 42 found at index 4 Searching for 50 in [3, 8, 15, 23, 42, 57, 71] Checking index 3, value 23 Checking index 5, value 57 Checking index 4, value 42 50 is not in the list
How it works
- The list must be sorted, otherwise throwing away half of it could skip the target.
lowandhighmark the part of the list still being searched, starting with the whole list.mid = (low + high) // 2picks the middle index, and the value there is compared with the target.- If the middle value is smaller, the target can only be to the right, so
lowmoves tomid + 1; if it is larger,highmoves tomid - 1. - When
lowpasseshigh, nothing is left to search, so the function returns -1 to mean not found.
Other ways to write it
Using recursion
Index of 57 is 5 (-1 means not found) Index of 10 is -1 (-1 means not found)
Instead of a loop, the function calls itself on the half that can still hold the target.
Using the bisect module
42 found at index 4 50 is not in the list
bisect_left() does the binary search and returns where the target is, or where it would go, so the program checks that the value there really matches.
Try it yourself
Count the checks for each search and compare that with how many a simple loop from the start of the list would need.
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