Effacer les filtres
Effacer les filtres

How to create binary search code

51 vues (au cours des 30 derniers jours)
Camden Nelson
Camden Nelson le 12 Fév 2023
Réponse apportée : Raghvi le 15 Fév 2023
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 commentaire
Voss
Voss le 12 Fév 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.

Connectez-vous pour commenter.

Réponses (1)

Raghvi
Raghvi le 15 Fév 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

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by