Sorting Arrays Using Array Methods
- Last UpdatedOct 29, 2024
- 2 minute read
The simplest way of sorting an array is to use the Sort() method:
!MyArray.Sort()
This is a no-result method that modifies the array by performing a sort in-situ.
The sort is into ascending order and will be an ASCII sort on an array of STRING elements and a NUMERIC sort on an array of REAL values.
The Sort() method returns the array itself as a list result, so it is possible to follow the call to the Sort() method immediately with a call to the Invert() method, which will return a descending sort:
!MyArray.Sort().Invert()
An alternative approach is an indirect sort using the method SortedIndices(), which returns a REAL array representing new index positions for the array elements in their sorted positions:
!NewPositions = !MyArray.SortedIndices()
The array can be sorted by applying the new index values using the ReIndex() method:
!MyArray.ReIndex(!NewPositions)
More importantly, the index values in !NewPositions can be used to sort other arrays as well.
To use some simple examples, imagine you have the array !Animals that contained:
|
Index |
Animal |
|
[1] |
Wombat |
|
[2] |
Kangaroo |
|
[3] |
Gnu |
|
[4] |
Aardvark |
|
[5] |
Antelope |
For example:
!Animals.Sort ()
This command would move the array elements so that they now appeared in the following order:
|
Index |
Animal |
|
[1] |
Aardvark |
|
[2] |
Antelope |
|
[3] |
Gnu |
|
[4] |
Kangaroo |
|
[5] |
Wombat |
On the other hand:
!Index = !Animals.SortedIndices()
This command would create a new array !index representing the subscript values of the array elements in !Animals, then sort these index values (without altering the array !Animals). After the sort, !index would look like this:
|
Index |
Subscript |
|
[1] |
4 |
|
[2] |
5 |
|
[3] |
3 |
|
[4] |
2 |
|
[5] |
1 |
The command:
!Index.Invert()
This command would result in !index now looking like:
|
Index |
Subscript |
|
[1] |
1 |
|
[2] |
2 |
|
[3] |
3 |
|
[4] |
5 |
|
[5] |
4 |