Implement Binary Search
function index = binarySearch(arr, target) % Performs binary search on a sorted array. % Returns the index of the target if found, otherwise -1. low = 1; high = length(arr); index = -1; % Edge case: empty array. if isempty(arr) return; end while low <= high % Calculate mid to pre...
This function implements the binary search algorithm to efficiently find a target value within a sorted array. It repeatedly divides the search interval in half. This is a fundamental algorithm used in searching database...
Binary search operates on a sorted array by repeatedly dividing the search interval in half. It starts with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, the search narrows to the lower half. Otherwise, it narrows to the upper half. This process is repeated until the value is found or the interval is empty. The time complexity is O(log N), where N is the number of elements in the array, due to the halving of the search space in each step. The space complexity is O(1) as it uses a constant amount of extra space. Key edge cases include an empty array, a target smaller than the smallest element, a target larger than the largest element, and the target being the first or last element. The loop invariant is that if the target exists, it must be within the `arr(low:high)` subarray.
function binarySearch(arr, target): low = 0 high = length(arr) - 1 index = -1 if arr is empty: return index while low <= high: mid = low + floor((high - low) / 2) if arr[mid] == target: index = mid return index else if a...