Why doesn't recursion in my mergeSort algorithm work?

2 views (last 30 days)
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);
sortedA = Arr;

Accepted Answer

Jethro Djan
Jethro Djan on 7 Oct 2022
Edited: Jethro Djan on 7 Oct 2022
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);
  1 Comment
Steven Lord
Steven Lord on 7 Oct 2022
That is correct. Numeric arrays in MATLAB behave like value classes, not handle classes. See this documentation page for more information.

Sign in to comment.

More Answers (0)




Community Treasure Hunt

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

Start Hunting!

Translated by