The SORT function returns a vector of subscripts that allow access to the elements of Array in ascending order.
Examples
Example 1
a = [4.0, 3.5, 7.0, 1.0, 1.1, 7.0, 7.0]
indices = sort(a)
asort = a[indices]
arev = a[reverse(indices)]
print, `indices needed to sort A: ${indices}`
print, `array A in sorted order: ${asort}`
print, `array A in reverse order: ${arev}`
IDL prints:
indices needed to sort A: [3, 4, 1, 0, 5, 6, 2]
array A in sorted order: [1.0, 1.1, 3.5, 4.0, 7.0, 7.0, 7.0]
array A in reverse order: [7.0, 7.0, 7.0, 4.0, 3.5, 1.1, 1.0]
Note: For the three elements equal to 7.0, the returned indices were in an arbitrary order. To preserve the original order of identical elements, you can use the STABLE keyword:
indices_stable = sort(a, /stable)
print, `indices needed to sort A: ${indices_stable}`
IDL prints:
indices needed to sort A: [3, 4, 1, 0, 2, 5, 6]
Example 2
Sorting NaN Values
When sorting data including Not A Number (NaN) values, the NaN entries are moved to the end of the resulting array. For example:
values = [ 500, !VALUES.F_NAN, -500 ]
PRINT, SORT(values)
IDL prints:
2 0 1
Syntax
Result = SORT(Array, /L64, /STABLE)
Return Value
The result is always a vector of integer type with the same number of elements as Array.
Note: If Array contains any identical elements, the order in which the identical elements are sorted is arbitrary and may vary between operating systems. Use the /STABLE keyword to preserve the order of identical elements.
Arguments
Array
The array to be sorted. Array can be any basic type of vector or array. String arrays are sorted using the ASCII collating sequence. Complex arrays are sorted by their magnitude. Array values which are Not A Number (NaN) are moved to the end of the resulting array.
Keywords
L64
By default, the result of SORT is 32-bit integer when possible, and 64-bit integer if the number of elements being sorted requires it. Set L64 to force 64-bit integers to be returned in all cases.
Note: Only 64-bit versions of IDL are capable of creating variables requiring a 64-bit sort. Check the value of !VERSION.MEMORY_BITS to see if your IDL is 64-bit or not.
STABLE
By default, if Array contains any identical elements, the order in which the identical elements are sorted is arbitrary. Set the STABLE keyword to force the algorithm to preserve the order of identical elements.
Version History
Original |
Introduced |
9.2 |
Added STABLE keyword
|
See Also
REVERSE, UNIQ, WHERE