|
||||||||
Bisection Search (Binary Search) - Python Automation and Machine Learning for ICs - - An Online Book - |
||||||||
Python Automation and Machine Learning for ICs http://www.globalsino.com/ICs/ | ||||||||
Chapter/Index: Introduction | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | Appendix | ||||||||
================================================================================= Bisection search, also known as binary search, is an algorithm used to find the position of a target value within a sorted sequence. The basic idea is to repeatedly divide the search interval in half until the target value is found or the interval is empty. In Python, bisection search is often implemented using the bisect module, which provides efficient algorithms for binary search on sorted sequences. An example of bisection search (code) is below: In this example above, bisect.bisect_left is used to find the index where the target value should be inserted in order to maintain the sorted order of the list. If the value at the found index is equal to the target, then the target is present in the list, and the index is returned. Otherwise, the target is not in the list, and -1 is returned. However, the list must be sorted for the bisection search to work correctly. Bisection search is a very efficient algorithm, especially for large datasets, as it reduces the search space by half at each step. Note that the bisect module above provides functions (bisect_left, bisect_right, bisect) to perform binary search on sorted sequences. For instance:
These functions do not check whether the input sequence is sorted, so it's crucial to ensure that the sequence is sorted before using them.
============================================
|
||||||||
================================================================================= | ||||||||
|
||||||||