Sort
From Xojo Documentation
(Redirected from Arrays.Sort)
Sorts the elements of a one-dimensional array in ascending order.
Usage
array.Sort
or
array.Sort(sortMethod As Delegate) (New in 2015r3)
Part | Description |
---|---|
array | The array to be sorted. |
sortMethod | A delegate method that will do the sorting. |
Notes
You can only use Sort with one-dimensional arrays for these data types: Single, Double, Integer (and all related Integer types), Text and String. String and Text sorting is case-insensitive.
A radix sort is currently used, although this is subject to change.
Sort only sorts in ascending order. If you need the results in descending order, fetch them from the array last to first after you have sorted it:
Sort uses the same ordering as the relational operators, with the exception that arrays of objects do not have Operator_Compare or Operator_Convert functions invoked on them.
Custom Sorting
By using the 2nd syntax with a delegate you can provide your own method to do the sorting. The delegate has two parameters, value1 and value2 (which are the same type as the array elements), and returns an integer. The delegate function should return a positive value if it considers value1 to be greater than value2, zero if it considers value1 and value2 to be equal, and a negative value if it considers value1 to be less than value2. An element that is less than another element will have a lower index in the array once sorting is finished.
Like the current Sort function, this modifies the array in place.
Delegate behavior:
- The delegate function must provide a stable ordering of the elements it is comparing. Failing to do so can result in infinite loops or other undefined behavior.
- The delegate function must not mutate or examine at the contents of the array while it is being sorted. Doing so will result in undefined behavior.
- The delegate must not be Nil. If Nil is passed, a NilObjectException is raised.
- The delegate function should not raise exceptions. If an exception is raised, the array is still valid and contains the same values but the order of elements is undefined.
Sample Code
This example sorts the aNames array.
names.Sort
// names = "Bob", "Jane", "Jim"
// For a descending sort, access the array in reverse order
Var reverseNames() As String
For i As Integer = names.LastRowIndex DownTo 0
reverseNames.Add(names(i))
Next
// reverseNames = "Jim", "Jane", "Bob"
Sort an array of Dates using a Delegate:
// This assumes the array is populated with non-Nil dates
If value1.SecondsFrom1970 > value2.SecondsFrom1970 Then Return 1
If value1.SecondsFrom1970 < value2.SecondsFrom1970 Then Return -1
Return 0
End Function
Var myArray() As Date
myArray.Add(New Date)
myArray.Add(New Date(2015, 8, 1))
myArray.Add(New Date(2014, 4, 1))
myArray.Add(New Date(2016, 11, 1))
myArray.Sort(AddressOf DateCompare)
// The array is now sorted
See Also
Var statement; Arrays concept for a complete list of functions; ParamArray keyword