searching for a number in a list
5 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Walter Roberson
on 2 Nov 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 Comments
Walter Roberson
on 2 Nov 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.
More Answers (1)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!