function found = binarySearch(target, data) found = 0; % target in data? we don't know yet % Nothing to find in an empty array: if isempty(data) return end % Now need to search array: % two ways to consider: [low, high] or [left, right] % where low <= high, left <= right low = 1; % first index (left) high = length(data); % last index (right) % While array indicies haven't crossed, keep searching: while low <= high mid = floor((low + high)/2); % if target is in middle of array, we've succeeded: if target==data(mid) found = mid; return; elseif target > data(mid) % L < M < T < H low = mid+1; % update left index (increase by 1 because M < T) elseif target < data(mid) % L < T < M < H high = mid-1; % update right index (decrease by 1 because M > T) else error('something terrible happened'); end end % found was set to zero, so if we reach down here, % item was not found