QUICKSORTX Subroutine

Purpose

Performs a quick-sort of an array by using a specified compare.

Syntax

QUICKSORTX( x,f)

Parameters

x
A one-dimensional array. If x is a BIT array, it must be BIT ALIGNED.
f
An ENTRY LIMITED expression that specifies the function invoked to perform all the required comparisons.

f must:

  • Be passed two POINTER BYVALUE arguments that hold the addresses of two elements from the array x
  • Have the attributes RETURNS( BYVALUE FIXED BINARY(31) )
  • Return one of the values -1, 0 or +1:
    • If the value of the first array element is less than the value of the second array element, then the returned value must be -1.
    • If the value of the first array element is equal to the value of the second array element, then the returned value must be 0.
    • If the value of the first array element is greater than the value of the second array element, then the returned value must be +1.

Description

The QUICKSORTX built-in subroutine performs a quick-sort, overwriting x with the sorted elements. The sorted array elements are stored in accordance with the result of the comparison function.

For example, you can sort in reverse order by reversing the less-than and greater-than logic in the comparison function.

If the result of the compare on two elements is equal, their order in the sorted array is unspecified.

Example

dcl arr (5) fixed bin (31) init (1,4,3,2,5);
dcl el entry limited;
el = func;
call quicksortx(arr, el);  /* same as quicksort. Ascending order */
put skip list (arr);  / * 1 2 3 4 5 */
el = func1;
call quicksortx(arr, el);  /* quicksort reversed, Descending order */
put skip list (arr);  /* 5 4 3 2 1 */

/* ascending */
   func: proc (p, q) returns(fixed bin (31) );

       dcl (p, q) pointer byvalue;

       dcl x fixed bin (31) based(p);
       dcl y fixed bin (31) based(q);

       /* asecending order */
       if x > y then return(1);
       if x = y then return(0);
       return (-1);
   end;

/* descending */
   func1: proc (p, q) returns(fixed bin (31) );

       dcl (p, q) pointer byvalue;

       dcl x fixed bin (31) based(p);
       dcl y fixed bin (31) based(q);

       /* decending order */
       if x > y then return(-1);
       if x = y then return(0);
       return (1);
   end;