![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/282959/image.png)
Binary Search - Descending order
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
James Tursa
el 8 de Abr. de 2020
Editada: James Tursa
el 8 de Abr. de 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.
Respuestas (1)
Divya Gaddipati
el 13 de Abr. de 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!
0 comentarios
Ver también
Categorías
Más información sobre File Operations en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!