VBA Binary Search Implementation
Function BinarySearch(arr() As Integer, target As Integer) As Integer ' Performs a binary search on a sorted array of integers. ' Returns the index of the target element if found, otherwise returns -1. Dim low As Integer Dim high As Integer Dim mid As Integer low = 0 high = UBoun...
This VBA code implements two binary search algorithms. The first, `BinarySearch`, is a standard implementation for finding an element in a sorted array. The second, `SearchInRotatedSortedArray`, is a more advanced versio...
Binary search operates on the principle of divide and conquer. By repeatedly dividing the search interval in half, it significantly reduces the number of comparisons needed. The time complexity is O(log n), where n is the number of elements in the array, making it extremely efficient for large datasets. The space complexity is O(1) for the iterative version. Key to its correctness is maintaining the invariant that the target, if present, always lies within the `low` and `high` bounds. Edge cases such as an empty array, a single-element array, or the target being at the boundaries are handled. The rotated array version adds complexity by first identifying the sorted sub-array to narrow down the search space effectively. Overflow in mid-point calculation is prevented by using `low + (high - low) / 2` instead of `(low + high) / 2`.
Function BinarySearch(array, target): Initialize low = 0, high = upper bound of array If array is empty, return -1 While low <= high: Calculate mid = low + (high - low) / 2 If array[mid] equals target, return mid If arra...