Unable to find bug in Problem 56040 which is a Binary Search problem on MATLAB Cody
Show older comments
I'm currently working on an implementation of the binary search algorithm in MATLAB, but I seem to have encountered a bug that I can't quite figure out. I would greatly appreciate your assistance in identifying and resolving the issue.
Here is the code:
function [loc, iter] = binarySearch(X, target)
% Initialize variables
found = false;
iter = 0;
low = 1;
high = numel(X);
while low < high
mid = floor((low + high) / 2);
iter = iter + 1;
if X(mid) == target
found = true;
break;
elseif X(mid) < target
low = mid + 1;
else
high = mid - 1;
end
end
% Check if the target is found
if found
loc = mid;
else
loc = -1; % Target value not found, set loc to -1
end
end
For test case
X = [1, 3, 5, 7, 9];
target = 7;
[loc, iter] = binarySearch(X, target)
The expected output is loc= 4 and iter is 2, while my output is loc = -1 and iter = 4.
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!