Recursively reversing large vector efficiently
2 views (last 30 days)
Show older comments
I am trying to write a code that will recursively compute reverse of given large vector . I have tried 2 codes one simple recursive code and other one iterative reversal code which flips 2 elements in one loop hence efficient
I want to replicate second code below in recursive way how can I approach that? Thank you for your time
% First code with simple recursion that flips end element one by one
function w=reversal_v2(v)
if length(v)==1
w= v;
else
w= [v(end),reversal_v2(v(1:end-1))];
end
% Second code with simple recursion that flips end element and first
% element together hence half the required time
b=1:1e4; %I/P vector
x=length(b); % To get length of vector
a=zeros(x);
for i=1:floor(length(b)/2) %Loop uses simple for loop and temp to substitute the values
tmp=b(i);
a(i)=b(x+1-i);
a(x+1-i)=tmp;
end
0 Comments
Answers (1)
per isakson
on 12 Aug 2021
Five ways to flip a row vector. The last one, reversal_v3(), answers your question. Recursion is by two order of magnitude slower than the for-loop.
v = 1:1e4;
tic, v(end:-1:1); toc
tic, flip(v); toc
tic, reversal_v2(v); toc
tic, SecondCode(v); toc
tic, reversal_v3(v); toc
function w = reversal_v2(v)
% First code with simple recursion that flips end element one by one
if length(v)==1
w = v;
else
w = [v(end),reversal_v2(v(1:end-1))];
end
end
function a = SecondCode( b )
% Second code with simple recursion that flips end element and first
% element together hence half the required time
% b=1:1e4; % I/P vector
x = length(b); % To get length of vector
a = zeros(1,x); % Create row vector
% Loop uses simple for loop and temp to substitute the values
for ii = 1:floor(length(b)/2)
tmp=b(ii);
a(ii)=b(x+1-ii);
a(x+1-ii)=tmp;
end
end
function w = reversal_v3(v)
% ... replicate second code below in recursive way ...
if length(v) <= 2
w = flip( v );
else
w = [ v(end), v(end-1), reversal_v3(v(1:end-2)) ];
end
end
See Also
Categories
Find more on Loops and Conditional Statements 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!