嘿,我是Matlab的新手,我为quicksort编写了一个简单的代码但是对于一些数组来说,大多数数组更长的数组,我的递归失败并给出了以下错误: "达到最大递归限制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;
答案 0 :(得分:0)
我注意到的第一件事是你没有包含停止标准,这意味着算法永远不会停止并且确实超过任何有限限制。其次,当您使用该值作为下一次迭代的pivot INDEX时,返回一个值为VALUE。
包括停止标准并返回索引i而不是值P解决了您的问题:
function A = quicksort(A,left,right)
if 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
end
function [sortedSub_array,PivotIndex] = 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;
PivotIndex = i-1;
end
顺便说一句,您可以通过使用较少的变量来显着缩短代码。包括对参数数量的检查允许您仅使用数组本身作为参数调用quicksort。
function A = quicksort(A,left,right)
if nargin == 1
left = 1;
right = numel(A);
end
if 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
end
function [A, i] = PartitionPivot(A,left,right)
P = A(left); % pivot
A([right left]) = A([left right]);
i = left;
% Partition
for j = left:right-1
if A(j) < P
A([j i]) = A([i j]);
i = i+1; % increment i only when swap occurs
end
end
A([right i]) = A([i right]);
end