how can I simplify this code?
Show older comments
is there any way to simplify this code? any help would be appreciated thanks.
function [idx, pairs_checked, scan_indices] = two_ended_search_1(x, target)
% TWO_ENDED_SEARCH Bidirectional scan from array ends toward center (arrays-only).
n = length(x);
% --- Edge case: empty array ---
if n == 0
idx = -1;
pairs_checked = zeros(0,2);
scan_indices = zeros(1,0);
return;
end
% --- Preallocate with conservative sizes ---
maxIters = ceil(n/2);
pairs_checked = zeros(maxIters, 2);
scan_indices = zeros(1, 2*maxIters); % at most two comparisons per iter
L = 1; R = n;
idx = -1;
pairCount = 0;
scanCount = 0;
while L <= R
% Record pair at start of iteration
pairCount = pairCount + 1;
pairs_checked(pairCount, :) = [L, R];
% Compare left
scanCount = scanCount + 1;
scan_indices(scanCount) = L;
if x(L) == target
idx = L;
break;
end
% If middle element already checked, stop (avoid duplicate compare)
if L == R
break;
end
% Compare right
scanCount = scanCount + 1;
scan_indices(scanCount) = R;
if x(R) == target
idx = R;
break;
end
% Move pointers inward
L = L + 1;
R = R - 1;
end
% Trim prealloc arrays to actual sizes
pairs_checked = pairs_checked(1:pairCount, :);
scan_indices = scan_indices(1:scanCount);
end
x = [5, 2, 3, 1, 9, 7, 9, 4, 8];
target = 4;
[idx, pairs_checked, scan_indices] = two_ended_search_1(x, target)
Accepted Answer
More Answers (0)
Categories
Find more on Constants and Test Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!