Bineary Search
Binary Search is a highly efficient searching algorithm that is used to find the position of a target value within a sorted array. It works by repeatedly dividing the search interval in half. Binary search is much faster than linear search, especially for large datasets, because it reduces the search space by half with each comparison.
How Binary Search Works:
Initial Setup:
Start with two pointers or indices: low (start of the array) and high (end of the array).
Find the Middle Element:
Calculate the middle index of the array:
mid=(low+high)/2
Compare the Middle Element with the target value:
If the middle element equals the target, return the index of the middle element.
If the target is smaller than the middle element, search the left half of the array by setting high = mid - 1.
If the target is larger than the middle element, search the right half by setting low = mid + 1.
Repeat:
Continue narrowing the search to the left or right half and recalculating the middle until the target is found or the search interval becomes empty (i.e., low > high).