Why doesn't recursion in my mergeSort algorithm work?

1 Ansicht (letzte 30 Tage)
Jethro Djan
Jethro Djan am 7 Okt. 2022
Bearbeitet: Jethro Djan am 7 Okt. 2022
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

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by