Last active
February 20, 2018 02:29
-
-
Save freeonterminate/7f85a276be0c12594a36e89fe00c466d to your computer and use it in GitHub Desktop.
Integer の QuickSort サンプル
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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