sort
Definition: | sequence res = sort(sequence s, integer order=ASCENDING) |
Description: | Sort s using a fast sorting algorithm. The elements of s can be any mix of atoms or sequences. |
pwa/p2js: | Supported, may however trigger p2js violations, that usually need sort(deep_copy(s)) to fix. |
Notes: |
Atoms come before sequences, and sequences are sorted "alphabetically" where the first elements are more significant
than the later elements, and with case sensitively (whereby 'Z' is before 'a').
The builtin constants ASCENDING and DESCENDING should be used for the order parameter, if required. That parameter was added for compatibility with Euphoria, and likewise the constants NORMAL_ORDER and REVERSE_ORDER, which are (as per Euphoria) just aliases for ASCENDING and DESCENDING respectively, and therefore behave identically. For a case-insensitive sort, see "Another Example" in tagset(). TIP: Should you experience a "p2js violation: relies on copy on write semantics" inside the sort() routine itself, use the call stack to determine where a call to deep_copy() should best be placed. Update (1.0.1): "without debug" in builtins/sort.e c/should (now) land you on the right line. In the majority of cases, s = sort(s) should work under with js without alteration
because s is a routine-local variable, but a deep_copy will be needed if it isn’t or res!=s or some other
variable still shares a reference to it. For obvious reasons sort() tries hard (very hard) to do everything
in-situ so you can’t be too upset or surprised when it needs a deep_copy(), and the latter is quite unlikely
to do any more work or eat any more memory than some pre-"with js" version of that code always used to anyway.
Similar advice applies to unique().
|
Example 1: |
x = 0 & sort({7,5,3,8}) & 0 -- x is set to {0, 3, 5, 7, 8, 0} |
Example 2: |
y = sort({"Smith", "Jones", "Doe", 5.5, 4, 6}) -- y is {4, 5.5, 6, "Doe", "Jones", "Smith"} |
Example 3: |
database = sort({{"Smith", 95.0, 29}, {"Jones", 77.2, 31}, {"Clinton", 88.7, 44}}) -- The 3 database "records" will be sorted by the first "field" -- i.e. by name. Where the first field (element) is equal it -- will be sorted by the second field etc. -- after sorting, database is: {{"Clinton", 88.7, 44}, {"Jones", 77.2, 31}, {"Smith", 95.0, 29}} |
Implementation: | See builtins\sort.e (an autoinclude) for details of the actual implementation. |
See Also: | custom_sort, compare, match, find |