Binary Search Demonstration

Binary Search Demonstration

Binary Search is an efficient search algorithm used to find the position of a target element in a sorted array or list. Unlike linear search, binary search repeatedly divides the search interval in half, drastically reducing the number of comparisons.

Key Requirement

The array must be sorted in ascending or descending order before applying binary search.

How Binary Search Works (Ascending Order)

Given a sorted array and a target value:

Set two pointers:

low = 0 (start of array)

high = n - 1 (end of array)

Find the middle index:
mid = (low + high) / 2

Compare:

If arr[mid] == target, return mid.

If arr[mid] > target, search in the left half (high = mid - 1).

If arr[mid] < target, search in the right half (low = mid + 1).

Repeat steps 2–3 until low > high (element not found).

Read More

Leave a comment