Recursively reversing large vector efficiently

2 views (last 30 days)
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

Answers (1)

per isakson
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
Elapsed time is 0.000255 seconds.
tic, flip(v); toc
Elapsed time is 0.000254 seconds.
tic, reversal_v2(v); toc
Elapsed time is 0.274852 seconds.
tic, SecondCode(v); toc
Elapsed time is 0.001037 seconds.
tic, reversal_v3(v); toc
Elapsed time is 0.097940 seconds.
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
  1 Comment
Rayyan Ramrajkar
Rayyan Ramrajkar on 14 Aug 2021
Thank you for your elaborate codes and I got the logic need to be implemented.
Regarding for loop vs recursion, I understand that simple loop approach is far more uperior than Recursion, but Recusrsion is must have requirement

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!