Previous: Ptr function To the Table of Content Next: Random function

- 4.62.2.64 -
Standard Units
System Unit
System Unit Procedures and Functions

QSort procedure

Targets: MS-DOS, OS/2, Win32


System Unit

QSort procedure performs a quick sort.

Declaration:
procedure QSort(base: Pointer; num, width: Integer;
                 function CompFunc conv arg_based
                 (const elem1, elem2: Pointer): Boolean);
Remarks:
The QSort procedure implements a quick-sort algorithm to sort an array of num elements, each of width bytes. The argument base is a pointer to the base of the array to be sorted. QSort replaces this array with the sorted elements. The argument CompFunc is a user-supplied function that compares two array elements and returns a value specifying their relationship. QSort calls the CompFunc function one or more times during the sort, passing pointers to two array elements on each call. The routine must compare the elements, then return one of the following values:
Return ValueDescription
< 0elem1 less than elem2
0elem1 equivalent to elem2
> 0elem1 greater than elem2
Example:
// This program uses qsort to sort
// an array of Integers in ascending order.
{$ifdef __GUI__}
  uses WinCRT;
{$endif}

function CompFunc conv arg_based
                   (const elem1, elem2: Pointer): Boolean;
begin
  Result := Integer(elem1^) > Integer(elem2^);
end;
 
procedure PrintArray(hdr: String; arg: array(1) of Integer);
var
  i: Integer;

begin
  Write(hdr);
  for i := 0 to high(arg)[0] do 
    Write(arg[i], ' ');
  Writeln;
end;
 
var
  a: array [0..9] of Integer;
  i: Integer;

begin
  for i := 0 to 9 do
    a[i] := Random(100) - Random(100);
  PrintArray('Initial: ', a);
  QSort(@a, 10, SizeOf(Integer), CompFunc);
  PrintArray(' Sorted: ', a);
end.



Previous: Ptr function To the Table of Content Next: Random function
Ptr function Table of Content Random function

- 4.62.2.64 -