Binary Search - Descending order

1 回表示 (過去 30 日間)
Queenie Chan
Queenie Chan 2020 年 4 月 8 日
回答済み: Divya Gaddipati 2020 年 4 月 13 日
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 Center および File ExchangeFile Operations についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by