How to create binary search code
91 次查看(过去 30 天)
显示 更早的评论
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 个评论
Voss
2023-2-12
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.
回答(1 个)
Raghvi
2023-2-15
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!