Why doesn't recursion in my mergeSort algorithm work?

I am following a book on algorithms and want to implement mergeSort myself. The problem is that I cannot get the desired ordering of my input array Arr. Have debugged and seen the problem but can't find a solution [which is that anything after mergeSort(Arr, p, q) is not executed at all]. In other languages like C, this would execute fine. Is there something missing [with respect to MATLAB] that will get the recursion to work?
function [sortedA] = mergeSort(Arr, p, r)
if p < r
q = floor((p + r)/2);
mergeSort(Arr, p, q);
mergeSort(Arr, q + 1, r);
merge(Arr, p, q, r);
end
sortedA = Arr;
end

 채택된 답변

Jethro Djan
Jethro Djan 2022년 10월 7일
편집: Jethro Djan 2022년 10월 7일
Apparently I didn't realise the fundamental error in my assumption which is that when dealing with arrays (or vectors in the case of MATLAB), I don't have default access to manipulating the pointers as would be in C. I have to deal with arrays by copying them around.
Edit: In case anyone is wondering what I ended up doing, it was something like this:
function [sortedA] = mergeSort(Arr, p, r)
if p < r
q = floor((p + r)/2);
leftArr = mergeSort(Arr(p:q));
rightArr = mergeSort(Arr(q+1:r));
sortedA = merge(leftArr, rightArr);
end
end

댓글 수: 1

That is correct. Numeric arrays in MATLAB behave like value classes, not handle classes. See this documentation page for more information.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2022a

질문:

2022년 10월 7일

편집:

2022년 10월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by