# ASORT()

Sort an array

Syntax

  ASORT( <aArray>, [<nStart>], [<nCount>], [<bSort>] ) --> aArray

Arguments

  <aArray> Array to be sorted.
  <nStart> The first element to start the sort from, default is 1.
  <nCount> Number of elements starting from <nStart> to sort, default is all elements.
  <bSort> Code block for sorting order, default is ascending order {| x, y | x < y }. The code block should accept two parameters and must return .T. if the sort is in order, .F. if not.

Returns

  <aArray> reference to the now sorted or NIL if the passed <aArray> is not an array.

Description

  ASORT() sort all or part of a given array. If <bSort> is omitted, the function expect <aArray> to be one dimensional array containing single data type (one of: Character, Date, Logical, Numeric) and sort this array in ascending order: Character are sorted by their ASCII value, Dates are sorted chronologically, Logical put .F. values before .T., Numeric are sorted by their value.
  If <bSort> is specified, it is used to handle the sorting order. With each time the block is evaluate, two array elements are passed to the code block, and <bSort> must return a logical value that state if those elements are in order (.T.) or not (.F.). Using this block you can sort multidimensional array, descending orders or even (but why would you want to do that) sort array that contain different data type.

Examples

          // sort numeric values in ascending order
          ASORT( { 3, 1, 4, 42, 5, 9 } )     // result: { 1, 3, 4, 5, 9, 42 }

          // sort character strings in descending lexical order
          aKeys := { "Ctrl", "Alt", "Delete" }
          bSort := {| x, y | UPPER( x ) > UPPER( y ) }
          ASORT( aKeys,,, bSort )      // result: { "Delete", "Ctrl", "Alt" }

          // sort two-dimensional array according to 2nd element of each pair
          aPair :=   { {"Sun",8}, {"Mon",1}, {"Tue",57}, {"Wed",-6} }
          ASORT( aPair,,, {| x, y | x[2] < y[2] } )
          // result: { {"Wed",-6}, {"Mon",1}, {"Sun",8}, {"Tue",57} }

Status

  Ready

Compliance

  Codeblock calling frequency and order differs from Clipper, since Harbour uses a different (faster) sorting algorithm (quicksort).

Files

  Library is vm

See Also

- ASCAN()
- EVAL()
- SORT