How to create binary search code
54 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentar
Voss
am 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.
Antworten (1)
Raghvi
am 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 Kommentare
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!