std / Sort
macOS Linux Windows wasm
#import "Sort";
In-place sorting of arrays by a comparator or a key, and ready-made comparators.
Procedures#
(array: [] $T, f: (T, T) -> $R) -> [] T
Sorts an array in place and returns the same view, so calls can be chained.
Person :: struct { name: string ; age: int ; }
people := Person.[.{"Ann" , 31 }, .{"Bo" , 25 }, .{"Cy" , 31 }];
by_age :: (a: Person, b: Person) -> int { return a.age - b.age; }
quick_sort (people, by_age);
assert (people[0 ].name == "Bo" );
age_of :: (p: Person) -> int { return p.age; }
quick_sort (people, age_of); // stable: Ann stays before Cy
assert (people[1 ].name == "Ann" && people[2 ].name == "Cy" );
numbers := int .[3 , 1 , 2 ];
sorted := quick_sort (numbers, (a: int , b: int ) -> int { return a - b; });
assert (sorted[0 ] == 1 && sorted[2 ] == 3 && sorted.data == numbers.data);↗ Run ▸
(a: float , b: float ) -> s64
A three-way comparator for quick_sort and intro_sort: -1, 0 or 1 for a < b, a tie and a > b.
values := float .[2.5 , -1 , 9 ];
quick_sort (values, compare_floats);
assert (values[0 ] == -1 && values[2 ] == 9 );
#import "Math" ;
with_nan := float .[FLOAT32_NAN, 3 , -2 ];
quick_sort (with_nan, compare_floats);
assert (with_nan[0 ] == -2 && with_nan[1 ] == 3 && with_nan[2 ] != with_nan[2 ]);↗ Run ▸
(a: string , b: string ) -> s64
A three-way comparator for strings, -1, 0 or 1, comparing bytes in order, so UTF-8 text sorts by code point and upper case comes before lower case. A string that is a prefix of another goes first.
names := string .["pear" , "Apple" , "fig" , "figs" ];
quick_sort (names, compare_strings);
assert (names[0 ] == "Apple" && names[1 ] == "fig" && names[2 ] == "figs" && names[3 ] == "pear" );↗ Run ▸