A simple and efficient iterative binary search algorithm.
Binary search is a classic algorithm used to efficiently find a target value in a sorted list. It works by repeatedly dividing the search interval in half. If the target value is equal to the middle element of the interval, the search is successful. Otherwise, the algorithm continues to search in the appropriate half of the list until the target value is found or the interval is empty.
- Initialization. Start with the left pointer
l
at the beginning of the list and the right pointerr
at the end of the list. - Iteration. Calculate the middle index
mid
as the average ofl
andr
whilel
is less than or equal tor
:- If the middle element
arr[mid]
is equal to the target valuevalue
, returnTrue
. - If
arr[mid]
is less than value, move the left pointerl
tomid + 1
. - If
arr[mid]
is greater than value, move the right pointerr
tomid - 1
.
- If the middle element
- Completion. If the loop exits without finding the value, return
False
.
The binary search algorithm has a time complexity of O(log n).
- Iterative Binary Search. The standard form, using a while loop.
- Recursive Binary Search. An alternative form using recursion.
- Finding the First or Last Occurrence. Modified versions to find the first or last occurrence of a value in a list with duplicates.
Binary search is commonly used in scenarios where efficient lookups in sorted data are required, such as:
- Database searching
- Real-time search systems
- Algorithmic problem solving
- Clone this repository
git clone https://github.com/torshin5ergey/python-playground.git
- Go to this project directory
cd python-playground/algo_arena/binary_search
- Run unit tests file
python -m unittest test_rabin_karp.py
This will run the unit tests and display the results. 4. Or use it in your project.
from binary_search import iterative_binary_search
Test class: TestBinarySearch
Included tests:
test_element_found
: True for existing elements.test_element_not_found
: False for non-existing elements.test_empty_array
: False for an empty array.test_single_element_array
: Correct work with a single-element array.test_large_array
: Correct work with large arrays efficiently.
from binary_search import iterative_binary_search
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
value = 4
print(iterative_binary_search(arr, value)) # Output: True
You have a sorted array of integers arr
and a target integer value
. Write the function iterative_binary_search
to determine if the target integer value
exists in the array arr
. Return True
if the target is found, otherwise return False
.
Sergey Torshin @torshin5ergey