Binary Search - Descending order

1 次查看(过去 30 天)
Queenie Chan
Queenie Chan 2020-4-8
Hi! I would like to know how to modify the code below so that it can work for vectors that are sorted in descending order, rather than ascending order. Your function should not sort the vector.
This is the code:
% FILENAME: binsearch-2.m
% SUBMISSION TIME: 08/04/2020 07:13:38 pm
% --- Begin file ---
function [left, right] = binsearch(vec,targetVal,left,right)
% SEARCH Binary search algorithm step.
% [left, right] = BINSEARCH(vec,targetVal,left,right) returns the end points
% produced by one step of the binary search algorithm with
% target value targetVal. The elements of vec must be in ascending order.
% Compute the mid-point by halving the distance between
% the end points and rounding to the nearest integer.
midPt = round((left + right)/2)
if vec(midPt) == targetVal
% targetVal has been found
left = midPt;
right = midPt;
elseif vec(midPt) > targetVal
% targetVal must be before midPt
right = midPt - 1;
else
% targetVal must be after midPt
left = midPt + 1;
end
  3 个评论
James Tursa
James Tursa 2020-4-8
@darova: More of your comments need to be answers ...
James Tursa
James Tursa 2020-4-8
编辑:James Tursa 2020-4-8
@Queenie: You realize that the posted code is only one step of a binary search, not the entire search algorithm, right? You would need to call this routine repeatedly.

请先登录,再进行评论。

回答(1 个)

Divya Gaddipati
Divya Gaddipati 2020-4-13
Hi,
You need to keep searching until you find the target. For this you need to add a while loop, which keeps reducing the search space.
Since, your vector is in descending order, if the middle value is less than the target, then you need to search on the left side, i.e, right = midPt - 1.
You need to modify your code as shown below:
function [left, right] = binsearch(vec, targetVal, left, right)
while (left < right)
midPt = floor((left + right)/2);
if vec(midPt) == targetVal
% targetVal has been found
left = midPt;
right = midPt;
elseif vec(midPt) < targetVal
% targetVal must be before midPt
right = midPt-1;
else
% targetVal must be after midPt
left = midPt + 1;
end
end
Hope this helps!

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by