Recursion Revisited - My Code:
3 ビュー (過去 30 日間)
古いコメントを表示
My code for the assigment of Recursion Revisited is not working for large vectors. Can you please explain me why it is not working although I have attempted to reduce the number of recursive function calls.
function w = reversal(v)
if length(v) <= 1
w = v;
else
f = v(1);
l = v(end);
vv = v(2:end-1);
w = [l reversal(vv) f];
end
end
0 件のコメント
回答 (1 件)
John D'Errico
2022 年 10 月 24 日
編集済み: John D'Errico
2022 年 10 月 24 日
Your code IS working acceptably. Of course, if you call it with a vector of length 1e6, or something like that, you can be getting millions of recursive calls. And that would blow your memory away. So why would you be surprised? Your code uses essentially N/2 recursive calls for a vector of length N. (Depends on if N is odd or even of course.)
Recursive solutions to problems are often nice, in the sense they are easy to write, and they just look neat. Hey, great. But that does not mean all recursive solutions to problems are efficient to implement. In fact, you often end up trading away a lot of memory required for that elegance in the way they look.
1 件のコメント
参考
カテゴリ
Help Center および File Exchange で Startup and Shutdown についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!