Binary Search - Descending order

11 views (last 30 days)
Queenie Chan
Queenie Chan on 8 Apr 2020
Answered: Divya Gaddipati on 13 Apr 2020
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 Comments
James Tursa
James Tursa on 8 Apr 2020
@darova: More of your comments need to be answers ...
James Tursa
James Tursa on 8 Apr 2020
Edited: James Tursa on 8 Apr 2020
@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.

Sign in to comment.

Answers (1)

Divya Gaddipati
Divya Gaddipati on 13 Apr 2020
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!

Community Treasure Hunt

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

Start Hunting!