searching for a number in a list
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2015-11-2
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 个评论
Walter Roberson
2015-11-2
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.
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!