Why doesn't recursion in my mergeSort algorithm work?

1 次查看(过去 30 天)
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 个评论
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 个)

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

产品


版本

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by