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 日

0 投票

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 件のコメント

Steven Lord
Steven Lord 2022 年 10 月 7 日
That is correct. Numeric arrays in MATLAB behave like value classes, not handle classes. See this documentation page for more information.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

製品

リリース

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