How to create binary search code

90 visualizaciones (últimos 30 días)
Camden Nelson
Camden Nelson el 12 de Feb. de 2023
Respondida: Raghvi el 15 de Feb. de 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 comentario
Voss
Voss el 12 de Feb. de 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.

Iniciar sesión para comentar.

Respuestas (1)

Raghvi
Raghvi el 15 de Feb. de 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

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by