# What Is binarySearch in Data Structure?

//

Scott Campbell

Binary search is a fundamental algorithm used in computer science and data structures. It allows for efficient searching of sorted arrays or lists by repeatedly dividing the search space in half. This technique drastically reduces the number of comparisons needed, making it much faster than linear search.

## How does binary search work?

The binary search algorithm works by comparing the Target value with the middle element of the array or list. If they match, the search is complete.

If the Target value is less than the middle element, the algorithm repeats on the left half of the array. If the Target value is greater, it repeats on the right half.

Here’s a step-by-step breakdown:

• Step 1: Set two pointers: low to point to the first element and high to point to the last element of the array.
• Step 2: Calculate mid, which is equal to (low + high) / 2.
• Step 3: Compare the Target value with arr[mid]:
• If they are equal, return mid as the index where the Target value was found.
• If arr[mid] is greater than the Target value, set high = mid – 1 and repeat from step 2.
• If arr[mid] is less than the Target value, set low = mid + 1 and repeat from step 2.
• Step 4: Repeat steps 2-3 until low becomes greater than high. This indicates that there are no more elements to search and that the Target value is not present in the array.

## Time complexity of binary search

The time complexity of binary search is O(log n), where n is the number of elements in the array. This logarithmic time complexity arises from the fact that with each comparison, the search space is divided in half.

## Benefits and limitations of binary search

Binary search offers several advantages over other searching algorithms:

• Efficiency: Binary search has a time complexity of O(log n), making it highly efficient for large datasets.
• Applicability: Binary search can be used on any sorted list or array, regardless of its size or data type.
• Simplicity: The algorithm is relatively straightforward and easy to implement.

However, binary search also has some limitations:

• Requirement of sorted data: Binary search requires the data to be sorted beforehand. If the data is unsorted or frequently changing, binary search may not be suitable.
• Lack of flexibility: Unlike linear search, which can handle unsorted data, binary search relies on a specific structure (sorted array/list).

## Conclusion

In summary, binary search is a powerful algorithm for efficiently searching sorted arrays or lists. By dividing the search space in half with each comparison, it quickly narrows down the possible locations of the Target value. Understanding how binary search works and its limitations can help you make informed decisions when implementing searching algorithms in your programs.