From Xojo Documentation
Sorts the elements of a one-dimensional array in ascending order.
array.Sort(sortMethod As Delegate) (New in 2015r3)
|array||The array to be sorted.|
|sortMethod||A delegate method that will do the sorting.|
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.
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.
- 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.
This example sorts the aNames array.
// 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 = "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
Var myArray() As DateTime
myArray.Add(New DateTime(2015, 8, 1))
myArray.Add(New DateTime(2014, 4, 1))
myArray.Add(New DateTime(2016, 11, 1))
// The array is now sorted