How to create binary search code
89 views (last 30 days)
Show older comments
I thought I had this code working yesterday but must've changed something on accident. I am not sure how to finish it to perform binary serach. It only says my value isn't present except when in the first index. See code below:
function [out] = BinSearch(x,A)
i = 1; % i is the leftmost index which is 1
j = length(A); % j is the rightmost index which is length(A)
while i < j
m = 1;
m = floor((i + j)/2); % Find middle of array
if x > A(m) % If userval is in the left half of array
i = m + 1;
else % Userval is in the right half of array
j = m;
end
end
if x == A(i) % If userval is in the first index
out = i;
else
out = ('Your number was not found in the array');
end
end
1 Comment
Voss
on 12 Feb 2023
The function seems like it will work ok when A is non-empty and sorted. Is the A you pass to the function sorted? If you want the function to work for arbitrary A, you can sort A inside the function and also handle the case when A is empty.
Answers (1)
Raghvi
on 15 Feb 2023
Hi Camden,
I understand you are having trouble with binary search function. I believe the problem was that you were checking x with first index (i) instead of middle index m. The following code worked for me:
function [out] = BinSearch(x,A)
i = 1; % i is the leftmost index which is 1
j = length(A); % j is the rightmost index which is length(A)
flag = 0;
while i <= j
m = ceil((i + j)/2); % Find middle of array
if A(m)==x
out = m;
flag = 1;
break;
elseif x > A(m) % If userval is in the left half of array
i = m + 1;
else % Userval is in the right half of array
j = m;
end
end
if flag == 0
out = ('Your number was not found in the array');
end
end
0 Comments
See Also
Categories
Find more on Shifting and Sorting Matrices 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!