Quicksort (with bounded stack usage)
 


procedure sort( var r : ArrayToSort; lo, up : integer );

var i, j : integer;
tempr : ArrayEntry;
begin
while up>lo do begin
i := lo;
j := up;
tempr := r[lo];
{*** Split file in two ***}
while i while r[j].k > tempr.k do
j := j-1;
r[i] := r[j];
while (i i := i+1;
r[j] := r[i]
end;
r[i] := tempr;
{*** Sort recursively ***}
sort(r,lo,i-1);
lo := i+1
end
end;

c version

sort( r, lo, up )
ArrayToSort r;
int lo, up;

{int i, j;
ArrayEntry tempr;
while ( up>lo ) {
i = lo;
j = up;
tempr = r[lo];
/*** Split file in two ***/
while ( i for ( ; r[j].k > tempr.k; j-- );
for ( r[i]=r[j]; i r[j] = r[i];
}
r[i] = tempr;
/*** Sort recursively, the smallest first ***/
if ( i-lo < up-i ) { sort(r,lo,i-1); lo = i+1; }
else { sort(r,i+1,up); up = i-1; }
}
}

(c) Shilpa Sayura Foundation 2006-2017