Sorting algorithms/Quicksort: Difference between revisions
Content deleted Content added
→{{header|Pascal}}: more complete example |
|||
Line 7,292: | Line 7,292: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{works with|FPC}} |
|||
<syntaxhighlight lang="pascal"> |
<syntaxhighlight lang="pascal"> |
||
program QSortDemo; |
|||
{ X is array of LongInt } |
|||
Procedure QuickSort ( Left, Right : LongInt ); |
|||
{$mode objfpc}{$h+}{$b-} |
|||
Var |
|||
i, j, |
|||
procedure QuickSort(var A: array of Integer); |
|||
tmp, pivot : LongInt; { tmp & pivot are the same type as the elements of array } |
|||
procedure QSort(L, R: Integer); |
|||
Begin |
|||
var |
|||
i:=Left; |
|||
I, J, Tmp, Pivot: Integer; |
|||
j:=Right; |
|||
begin |
|||
pivot := X[(Left + Right) shr 1]; // pivot := X[(Left + Right) div 2] |
|||
if R - L < 1 then exit; |
|||
Repeat |
|||
I := L; J := R; |
|||
{$push}{$q-}{$r-}Pivot := A[(L + R) shr 1];{$pop} |
|||
While pivot < X[j] Do dec(j); // j:=j-1; |
|||
repeat |
|||
If i<=j Then Begin |
|||
while A[I] < Pivot do Inc(I); |
|||
while A[J] > Pivot do Dec(J); |
|||
if I <= J then begin |
|||
Tmp := A[I]; |
|||
A[I] := A[J]; |
|||
A[J] := Tmp; |
|||
Inc(I); Dec(J); |
|||
Until i>j; |
|||
end; |
|||
If Left<j Then QuickSort(Left,j); |
|||
until I > J; |
|||
If i<Right Then QuickSort(i,Right); |
|||
QSort(L, J); |
|||
End; |
|||
QSort(I, R); |
|||
end; |
|||
begin |
|||
QSort(0, High(A)); |
|||
end; |
|||
procedure PrintArray(const A: array of Integer); |
|||
var |
|||
I: Integer; |
|||
begin |
|||
Write('['); |
|||
for I := 0 to High(A) do |
|||
if I < High(A) then Write(A[I], ', ') |
|||
else Write(A[I]); |
|||
WriteLn(']'); |
|||
end; |
|||
var |
|||
a: array[-7..6] of Integer = (-34, -20, 30, 13, 36, -10, 5, -25, 9, 19, 35, -50, 29, 11); |
|||
begin |
|||
QuickSort(a); |
|||
PrintArray(a); |
|||
end. |
|||
</syntaxhighlight> |
</syntaxhighlight> |
||
{{out}} |
|||
<pre> |
|||
[-50, -34, -25, -20, -10, 5, 9, 11, 13, 19, 29, 30, 35, 36] |
|||
</pre> |
|||
=={{header|Perl}}== |
=={{header|Perl}}== |