MatLab でクイック ソートを実装しようとしています。2 つの関数があります。1 つは指定されたリストを 2 つの小さなリストに分割し、1 つはピボットよりも大きく、もう 1 つは小さいリストに分割します。2 番目の関数は、クイック ソートを再帰的に呼び出し、次に小さいリストを反復処理して、クイック ソートを再度呼び出します。私のコードは以下です。ランダムに生成された 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