クイックソートは、特定の条件でスタックオーバーフロー例外が発生する可能性があると思います。クイックソートとスタックオーバーフローの例外
ソート処理中にピボット要素を選択するには、基本的に2つの方法があります。ピボット値は、ソートされた範囲の中央の要素またはランダムに選択された要素(ソートされた範囲内)です。 2つ目の方法(ランダム)は、最初の方法よりもスタックオーバーフローが起こりにくいのですか?私に助言してもらえますか?
procedure QuickSort(lLowBound, lHighBound: integer; lCompare: TListSortCompare;
lSwap: TListSortSwap);
procedure Sort(lLowIndex, lHighIndex: integer);
var
lLeft: Integer;
lRight: Integer;
lPivot: Integer;
lLeftCompare: Integer;
lRightCompare: Integer;
begin
repeat
lLeft := lLowIndex;
lRight := lHighIndex;
lPivot := (lLowIndex + lHighIndex) div 2; //the pivot as the element in the middle
//lPivot := lLowIndex + Random(lHighIndex - lLowIndex + 1); //the pivot chosen randomly
repeat
lLeftCompare := lCompare(lLeft, lPivot);
while lLeftCompare < 0 do
begin
Inc(lLeft);
lLeftCompare := lCompare(lLeft, lPivot);
end;
lRightCompare := lCompare(lRight, lPivot);
while lRightCompare > 0 do
begin
Dec(lRight);
lRightCompare := lCompare(lRight, lPivot);
end;
if lLeft <= lRight then
begin
if not ((lLeftCompare = 0) and (lRightCompare = 0)) then
begin
lSwap(lRight, lLeft);
if lPivot = lLeft then
lPivot := lRight
else if lPivot = lRight then
lPivot := lLeft;
end;
Inc(lLeft);
Dec(lRight);
end;
until lLeft > lRight;
if (lLowIndex < lRight) then
Sort(lLowIndex, lRight);
lLowIndex := lLeft;
until lLeft >= lHighIndex;
end;
begin
if lHighBound > lLowBound then
Sort(lLowBound, lHighBound);
end;
事前にあなたのアドバイスをありがとう:ここ
は、クイックソート(デルファイ)の私のバージョンです!
マリウス。
ご協力いただきありがとうございます。私はあなたが提案した方法でクイックソートの反復バージョンを作ることができました。 –