What is Binary Search?
Binary search is an efficient algorithm used to find a specific element in a sorted array or list. It works by repeatedly dividing the search space in half until the target element is found or determined to be absent.
How does Binary Search work?
Binary search starts by comparing the target element with the middle element of the array. If they are equal, the search is complete. If the target element is smaller, the search continues on the lower half of the array; otherwise, it continues on the upper half.
This process is repeated until the target element is found or the search space is empty.
Binary Search Demonstration
Have a go with the binary search demonstration below.
Pros & Cons
Pros and Cons of Binary Search
- Efficient searching algorithm
- Divides the search space in half with each comparison
- Requires a sorted array, ensuring data integrity
- Can quickly find a desired element in a large data set
- Requires a sorted array, making initial setup time-consuming
- Not suitable for dynamic data sets that frequently change
- Cannot handle unsorted or unordered data
- Implementation is more complex than a linear search
Binary Search Python Code