我正在尝试在 MatLab 中实现快速排序。我有两个函数,一个将给定列表拆分为两个较小的列表,一个大于枢轴,一个小于枢轴。第二个函数递归调用快速排序并迭代到下一个较小的列表,再次调用快速排序。我的代码如下。当我用我的 300 个随机生成的数字列表运行代码时,我收到错误“内存不足。可能的原因是程序内的无限递归。”。
function [ less, pivot, greater ] = SplitList( list, pivotindex )
%List Splitting Function
%In order to preform quick sort you firts must be able to split the list
%into two, one which is greater than, and one which is less than the pivot.
pivot = list(1,pivotindex);
greater = [];
less = [];
for l = 1:length(list)
if list(1,l) > pivot
greater = [greater list(1, l)];
else if list(1,l) <= pivot
less = [less list(1, l)];
end
end
end
end
function [ qs_list ] = quick_sort( list )
%Recursive Quick Sort
% quick sort algorithm to sort a list of numbers
%set (0,'RecursionLimit',1000);
pivotindex = round(length(list)/2); %sets pivot at the median value of the array
if length(list) > 1
[ less, pivot, greater ] = SplitList( list, pivotindex ); %calls the SplitList function
qs_list = [quick_sort(less) pivot quick_sort(greater)]; %calls quick_sort within the function
else
qs_list = list;
end
end