필터 지우기
필터 지우기

Binary Search - Descending order

조회 수: 6 (최근 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 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