Main sections
SORTARRAY
SORTARRAY array[], cmp%
Sorts an array in ascending order - i.e. array[0] has the smallest element.
The sorting algorithm can be applied to arrays of TYPEs, too. When used with an array of TYPEs, the first member variable of the TYPE is used for the comparison.
The parameter cmp% can be used to inject your own comparison function for the sorting algorithm. If you leave this parameter equal to 0, the default behaviour as described above will be used.
cmp% must be the address of a function, accepting 2 x BYREF arguments that are the type of the array's elements.
Attention: If the function is supplied different parameters, the program will crash.
LOCAL arr[]
// default sort
Fill(arr[])
SORTARRAY arr[], 0
FOR i=0 TO LEN(arr[])-1
PRINT arr[i], 0, i*16
NEXT
// sort by function
Fill(arr[])
SORTARRAY arr[], ADDRESSOF(compare)
FOR i=0 TO LEN(arr[])-1
PRINT arr[i], 100, i*16
NEXT
// inverse sort by function
Fill(arr[])
SORTARRAY arr[], ADDRESSOF(inverse_compare)
FOR i=0 TO LEN(arr[])-1
PRINT arr[i], 200, i*16
NEXT
SHOWSCREEN
MOUSEWAIT
FUNCTION Fill: arr[]
DIM arr[0]
FOR i=0 TO 10
DIMPUSH arr[], RND(100)
NEXT
ENDFUNCTION
FUNCTION compare: BYREF a, BYREF b
IF a<b THEN RETURN -1
IF a>b THEN RETURN 1
RETURN 0
ENDFUNCTION
FUNCTION inverse_compare: BYREF a, BYREF b
IF a<b THEN RETURN 1
IF a>b THEN RETURN -1
RETURN 0
ENDFUNCTION