xHarbour Reference Documentation > Function Reference |
Sorts an array.
ASort( <aArray>, [<nStart>], [<nCount>], [<bSort>] ) --> aArray
When a code block is specified, it must be declared with two parameters and must return a logical value. The code block receives the values of two adjacent array elements. When the code block returns .T. (true), the first code block parameter is considered smaller than the second. If .F. (false) is returned, the first code block parameter is larger.
The function returns a reference to <aArray>.
ASort() sorts an array entirely or partially by the values stored in its elements. If the code block <bSort> is omitted, the function expects <aArray> to be a one dimensional array containing simple data types. The values are sorted in ascending order. Character strings are sorted by their ASCII values, dates are sorted chronologically, Logical .F. (false) is smaller than .T. (true), and Numerics are sorted by their value.
If <bSort> is specified, it is used to define the comparison rule for "smaller". The code block must have two parameters which receive the values of two array elements. The first code block parameter is considered smaller, when the code block returns .T. (true), otherwise it is considered larger than the second code block parameter.
The definition of an appropriate comparison rule allows for sorting an array in descending order, and/or to sort multi-dimensional arrays.
See also: | AEval(), AScan(), Eval(), SORT |
Category: | Array functions |
Source: | vm\arrayshb.c |
LIB: | xhb.lib |
DLL: | xhbdll.dll |
// The example demonstrates the sorting of one- and two-dimensional // arrays in ascending and descending order. PROCEDURE Main() LOCAL i, aNum := { 3, 1, 4, 42 } LOCAL aNames := { { "gilbert", 1 }, ; { "eats" , 2 }, ; { "grape" , 3 } } // one-dimensional array ? "Ascending: " ASort( aNum ) FOR i := 1 TO Len( aNum ) ?? aNum[i] // result: 1 3 4 42 NEXT ? "Descending: " ASort( aNum ,,, {|x,y| x > y } ) FOR i := 1 TO Len( aNum ) // result: 42 4 3 1 ?? aNum[i] NEXT // two-dimensional array sorted by second column ? "Descending: " ASort( aNames ,,, {|x,y| x[2] > y[2] } ) FOR i := 1 TO Len( aNames ) ? aNames[i,1] NEXT // result: // grape // eats // gilbert RETURN
http://www.xHarbour.com