Binary Search Math
Binary Search Math
mid = (max+min) / 2
if list[mid] >key then
max = mid-1
min = mid+1
else
return mid
end if
end while
return false
Ans:
Binary Search is an efficient algorithm for finding a specific value within a sorted array. It works
by repeatedly dividing the search interval in half. Here's a breakdown of the provided code:
Function Parameters:
Algorithm Steps:
■ If list[mid] is greater than key, the target element must lie in the left half of the
■ If list[mid] is equal to key, the target element is found, and the function returns
mid.
○ The function returns false, indicating that the key is not present in the array.
Key Points:
● Efficiency: Binary Search has a time complexity of O(log n), making it significantly faster
than linear search for large arrays.
● Precondition: The array must be sorted for Binary Search to work correctly.
● Integer Division: Ensure that mid is calculated using integer division to avoid potential
floating-point issues.
Example:
Consider the sorted array: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
2. First Iteration:
○ mid = (0 + 9) / 2 = 4
3. Second Iteration:
○ mid = (0 + 3) / 2 = 1
5. Fourth Iteration:
○ mid = (3 + 3) / 2 = 3
○ list[mid] = 12 = key, so the function returns 3.
You can implement Binary Search in various programming languages, such as Python, Java,
C++, etc. The core logic remains the same, but the syntax and specific implementation details
may vary.
Additional Considerations:
● Edge Cases: Consider edge cases like empty arrays or arrays with only one element.
By understanding these concepts and the implementation details, you can effectively use Binary