searching for a number in a list
5 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
MG
el 2 de Nov. de 2015
Comentada: Walter Roberson
el 2 de Nov. de 2015
Hi, I made a code below which I need to use to find a value in a list L. Supposing I have the following list L = [1 3 5 9 2 4 0 8]. If I call searchForIt(L, 2) I should get 5. But this is not what happens in matlab. I can't seem to figure out why that is.
function [Ind] = searchForIt(L, num)
% Ind = index of first occurence (if any) of num in L
% L is a list of numbers that is unsorted
% num is the number I am looking for in the list
Ind = [];
left_Ind = 1;
right_Ind = length(L);
while right_Ind > left_Ind;
mid_Ind = floor((left_Ind + right_Ind)/2);
if L(mid_Ind) == num;
elseif L(mid_Ind) < num;
left_Ind = mid_Ind + 1;
else right_Ind = mid_Ind - 1;
end
end
end
0 comentarios
Respuesta aceptada
Walter Roberson
el 2 de Nov. de 2015
That is code for a binary search, which requires that the list L be sorted already. As your list is not sorted, you will not get the answers you expect.
13 comentarios
Walter Roberson
el 2 de Nov. de 2015
You can still use "while right_Ind > left_Ind" but if you do then afterwards you need to check in case the two are equal and that the number is found there. But it is easier to just use >= instead of > to cover the situation.
I have no idea what your assignment said. The usual way to handle the situation is to not use a binary search on an unsorted matrix. You might wonder what is wrong with doing the sort followed by a binary search, and the answer to that is that sorting is slower than a linear search for a single target value, as that involves at most length(L) comparisons but the best sort algorithms in the world are never less than length(L)*log(length(L)) for some arrangements of L.
If you are going to use sort() then read the documentation for it more carefully and see what other information you can ask it to return.
Más respuestas (1)
Ver también
Categorías
Más información sobre Startup and Shutdown en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!