I need help arranging a vector using recursion please.
조회 수: 10 (최근 30일)
이전 댓글 표시
I am working on a function called vecSort that is supposed to arrange a vector from the smallest element to the largest using recursion. I cannot use the 'sort' function or any function similar to it. I have to use the min and/or max functions. This is what I have so far:
function vectorSort(vec)
L=length(vec);
if L<1
vec=[];
elseif L==1
vec=vec;
else i>1;
I have set the terminating condition but I cannot figure out how to get function to call on itself to arrange the vector from the minimum element to the largest element.
댓글 수: 3
Walter Roberson
2017년 11월 5일
You cannot sort recursively in any useful way unless you also have a phase for combining already-sorted regions.
채택된 답변
Walter Roberson
2017년 11월 6일
Since you do not have a re-combination phase, your "recursive" function will have to be written from a theoretical point of view, just to prove that it can be done, instead of from a practical point of view. You will need to change your strategy into something closer to a bubble sort, and see https://www.mathworks.com/matlabcentral/answers/361333-help-i-need-to-convert-numbers-into-english-words-using-recursion#answer_285821 on how to transform the "for" loops into recursion.
I would never write a recursive sort this way, and I would never recommend teaching about recursion in this way.
If you had a phase designed to merge the results of two vectors that were already sorted then then that can be done usefully and effectively with recursion. But as you appear to be insisting that you do not have such a phase, you will have to use the ugly theoretical transform between for and recursion, just to satisfy your assignment of having used recursion.
댓글 수: 5
Walter Roberson
2020년 9월 22일
Well, it would fail on NaN. Do you have NaN in your vector, Neha Prajapati ? If so then where do you want them to be sorted relative to the numbers?
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!