【发布时间】:2017-09-06 20:54:28
【问题描述】:
我正在尝试使用 Lomuto's Partitiong 方法实现迭代 QuickSort,因此我正在尝试实现一个 stack,其中包含定义的一对索引要分区的子数组,使用struct 和两个fields 组成的数组:iBeg、iEnd 并仅存储/访问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)
预期输出:
[1, 2, 3, 4, 5, 6, 7, 9]
当前输出:从不从函数返回,仅通过强制制动停止:ctrl + c。
注意:分区函数的实现和应用与指出的可能重复的不同。
【问题讨论】:
-
你用什么输入来测试?
-
@Wolfie 什么是迭代实现中的“递归深度”?将来遇到同样问题的人是否有可能在递归实现中为其迭代实现寻求解决方案?
-
算法相似(当然,它们都是快速排序),但实现略有不同,因为您的方法不是递归的。链接问题失败的原因与您的代码失败的原因相同,症状 由于方法不同(无限循环与无限递归),但解决方案是相同的。随意将问题留在这里,因为它可能对其他人有所帮助,但请注意它可能会作为重复项而关闭。旁注:您的代码中有错字,您的函数称为
iterativeQucikSort而不是iterativeQuickSort -
我在所有方面都同意@Wolfie。把这个留在这里,它仍然是一个很好的路标。
-
另外值得注意的是,您的代码是使用 Octave 编写的,而不是 MATLAB。特别是,
!=不是有效的 MATLAB 语法,如果您打算将其用于两种语言,则应将~=用于“不等于”。
标签: algorithm matlab sorting octave quicksort