Void sort(var [a] xs, Int(a, a) sortfn=compare)
Arguments
xs: The array to sortsortfn: Optionally, a user-defined comparison function.
Usage
Sort an array in-place using the quicksort algorithm. By default this uses the compare function and sorts in ascending order, but it can instead use a user supplied compare function.
xs = [3,5,1,2,6,1];
sort(xs); // [1,1,2,3,5,6]
Comparison functions should return 0 if the values are identical, less than zero if the first value passed to the function is 'smaller', and more than zero if the second value is 'bigger'. In this context, 'smaller' values are moved to the start of the array, and 'bigger' values to the end. The following example has a simple function to sort an array of Ints into descending order.
Int rsort(Int a, Int b) {
return b-a;
}
Void main() {
xs = [3,5,1,2,6,1];
sort(xs,rsort); // [6,5,3,2,1,1]
}
Values that are identical for the purposes of the sorting function will be placed in an undefined order relative to each other.
Related
- The sorted function returns a sorted copy of the array, rather than sorting in place.