我尝试使用Lomuto's Partitiong方法实现迭代 QuickSort ,因此我尝试实现堆栈保存一对索引,用于定义要分区的子数组,使用struct
数组和两个fields
:iBeg
,iEnd
并仅存储/访问{{1}元素。
以下是代码:
end
明显愚蠢的数组赋值function [sorted] = iterativeQuickSort(A)
% Accepts 1xN unsorted integer array.
% Returns a sorted copy.
% See also Partition.
% Starting and ending indexes of unsorted array.
iBeg = 1;
iEnd = numel(A);
% Struct holding A's subarrays star/end indexes resulting from partitioning.
stack_elem = struct('iBeg', iBeg, 'iEnd', iEnd);
stack(end + 1) = stack_elem; % push on stack
while numel(stack) != 0
% Extract last pair of indexes.
iBeg = stack(end).iBeg;
iEnd = stack(end).iEnd;
stack(end) = []; % pop from stack
% Get pivot index and array after rearranging elements around the pivot.
[B, pivotIndex] = Partition(A, iBeg, iEnd);
A = B;
% Store indexes of the next two subarrays defined by the pivot index,
% if their sizes are > 0.
if pivotIndex - 1 > iBeg
stack_elem = struct('iBeg', iBeg, 'iEnd', pivotIndex - 1);
stack(end + 1) = stack_elem;
end
if pivotIndex + 1 < iEnd
stack_elem = struct('iBeg', pivotIndex + 1, 'iEnd', iEnd);
stack(end + 1) = stack_elem;
end
end
sorted = A;
end
function [A, pivotIndex] = Partition (A, iBeg, iEnd)
% Accepts 1xN integer array.
% Two integers - start and end indexes current subarray of A.
% Returns index of pivot element of current subarray partition
% and A after swaps.
pivotValue = A(iEnd); % Choose last element to be pivot.
pivotIndex = iBeg; % Initialize pivot index to start of subarray.
for i = iBeg : iEnd % Iterate over current subarray
if A(i) <= pivotValue % Push elements <= pivot in front of pivot index.
% Place element at i-th position before element with pivot index.
[A(i), A(pivotIndex)] = swapElements(A(pivotIndex), A(i));
% Account for the swap, go to next element.
pivotIndex = pivotIndex + 1;
end
end
% Bring the element used as pivot to its place
[A(iEnd), A(pivotIndex)] = swapElements(A(pivotIndex), A(iEnd));
end
function [elem2, elem1] = swapElements(elem1, elem2)
[elem2, elem1] = deal(elem1, elem2);
end
用于表示在执行函数A = B
后保留swaps
引起的元素更改。
当前状态似乎是一个无限循环,其原因我无法识别,因此任何建议和建议都将不胜感激!
输入:
Partition(A, iBeg, iEnd)
预期产出:
A = [5, 4, 6, 2, 9, 1, 7, 3];
S = iterativeQuickSort(A)
电流输出:永不从功能返回,仅通过强制制动停止:ctrl + c。
注意:分区功能的实现和应用与可能重复的那个不同。
答案 0 :(得分:2)
您的Partition
函数出错。如果你看一下维基百科页面上的伪代码,你会发现循环条件是:
for j := lo to hi - 1 do
Partition
功能中的相应行是:
for i = iBeg : iEnd % Iterate over current subarray
转到iEnd
代替iEnd - 1
,您需要将数据透视值与自身进行比较,最后得到一个偏离一个的数据透视索引。只需将此行更改为:
for i = iBeg : iEnd-1 % Iterate over current subarray