how can I simplify this code?
Ältere Kommentare anzeigen
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)
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Constants and Test Matrices finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!