Skip to content

Instantly share code, notes, and snippets.

@freeonterminate
Last active February 20, 2018 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freeonterminate/7f85a276be0c12594a36e89fe00c466d to your computer and use it in GitHub Desktop.
Save freeonterminate/7f85a276be0c12594a36e89fe00c466d to your computer and use it in GitHub Desktop.
Integer の QuickSort サンプル
program QuickSortSample;
procedure QuickSort(var ioInt: array of Integer);
procedure QuickSortBody(iLo, iHi: Integer);
var
Min, Max, Mid: Integer;
tmpInt: Integer;
begin
repeat
Min := iLo;
Max := iHi;
// 適切な中央値を探すのが大変なので、ここでは配列の中央を使っている
// もちろん、配列の中央に中央値があるわけではない
Mid := (iLo + iHi) shr 1;
repeat
while (ioInt[Min] < ioInt[Mid]) do
Inc(Min);
while (ioInt[Max] > ioInt[Mid]) do
Dec(Max);
if (Min <= Max) then
begin
tmpInt := ioInt[Min];
ioInt[Min] := ioInt[Max];
ioInt[Max] := tmpInt;
if (Mid = Min) then
Mid := Max
else if (Mid = Max) then
Mid := Min;
Inc(Min);
Dec(Max);
end;
until (Min > Max);
if (iLo < Max) then
QuickSortBody(iLo, Max);
iLo := Min;
until (Min >= iHi);
end;
begin
if (Length(ioInt) > 1) then
QuickSortBody(Low(ioInt), High(ioInt));
end;
var
Nums: array of Integer = [8, 7, 5, 9, 1];
N: Integer;
begin
QuickSort(Nums);
for N in Nums do
Writeln(N);
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment