【发布时间】:2014-09-27 00:04:25
【问题描述】:
嘿,我是 Matlab 的新手,我为快速排序编写了一个简单的代码,但对于某些数组,通常是较长的数组,我的递归失败并给出以下错误: “达到最大递归限制 500。使用 set(0,'RecursionLimit',N) 更改 限制。请注意,超出可用堆栈空间可能会使 MATLAB 和/或 你的电脑。
quic 中的错误”
我认为我的基本情况可能是错误的,但我无法弄清楚我做错了什么。一些帮助将不胜感激。
function A = quicksort(A,left,right)
[A, pivot] = PartitionPivot(A, left, right); %chosen pivot
A = quicksort(A, left, pivot-1); %scan from the left of the array until an element greater than pivot is found and swap it with the element less than the pivot on the right of the pivot
A = quicksort(A, pivot+1, right); %scan from the right of the array until an element less than pivot is found and swap it with the element greater than the pivot on the left of the pivot
end
function [sortedSub_array,Pivot] = PartitionPivot(Sub_array,left_index,right_index)
% Initialization
S = Sub_array;
left = left_index;
right = right_index;
P = S(left); %pivot
i = left+1;
% Partition
for j = i:right
if S(j) < P
temp1 = S(j);
S(j) = S(i);
S(i) = temp1;
i = i+1; %increment i only when swap occurs
end
end
swap1 = S(left);
S(left) = S(i-1);
S(i-1) = swap1;
sortedSub_array = S;
Pivot = P;
【问题讨论】:
标签: matlab recursion quicksort