Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

How Binary Search Works

1. Initial Setup: Binary search starts with three pointers: the low, mid, and high
pointers. Initially, the low pointer is set to the first index of the array, and the high
pointer is set to the last index.
2. Midpoint and Comparison: The algorithm calculates the midpoint of the current
subarray being considered (the part of the array between the low and high
pointers) and compares the value at the midpoint with the target value.
 If the target value is equal to the value at the midpoint, the search is
successful, and the position of the midpoint is returned.
 If the target value is less than the value at the midpoint, the algorithm
repeats its process on the subarray to the left of the midpoint (the target
can only be in the left half since the array is sorted).
 If the target value is greater than the value at the midpoint, the search
continues on the subarray to the right of the midpoint.
3. Narrowing Down: This process of dividing the array in half and determining
which side of the array to continue the search is repeated until the target value is
found or until the subarray becomes empty (meaning the value is not in the
array).

Characteristics and Performance

 Efficiency: Binary search is much more efficient than linear search for large
datasets because it reduces the search space by half with each step. The time
complexity of binary search is O(log n), where n is the number of elements in the
array.
 Requirement for Sorted Array: A key requirement for binary search to work is
that the dataset must be sorted. If the data is not sorted, binary search cannot be
applied directly.
 Applications: Binary search is widely used in practical computing tasks, including
in database indexing, searching in large texts, and in algorithms that require
searching, such as finding the square root of a number or binary search trees
operations.

Limitations

While binary search is highly efficient for sorted arrays, its performance depends on the
data being sorted. Additionally, binary search is traditionally implemented on arrays, and
its performance can be less optimal on linked lists due to the sequential access nature of
linked lists, which makes finding the midpoint more time-consuming.
In summary, binary search is a cornerstone algorithm in computer science for efficiently
finding elements within a sorted dataset. Its log(n) complexity makes it a preferred
choice for search operations in large datasets, highlighting the importance of
understanding and implementing binary search in software development and
algorithmic problem-solving.

You might also like