Sort using a custom comparator: Difference between revisions

m
(→‎{{header|Pascal}}: added example)
m (→‎{{header|Wren}}: Minor tidy)
 
(7 intermediate revisions by 6 users not shown)
Line 879:
 
===Vanilla===
 
While vanilla AppleScript doesn't have sort facilities of its own, a customisable sort written in vanilla, such as [https://macscripter.net/viewtopic.php?pid=194430#p194430 this one on MacScripter], can be fed user-defined comparison handlers to do practically any kind of sorting. The following assumes that the customisable sort just mentioned has been compiled and saved in a suitable "Script Libraries" folder as "Custom Iterative Ternary Merge Sort.scpt":
 
<syntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- OS X 10.9 (Mavericks) or later
use sorter : script "Custom Iterative Ternary Merge Sort"¬
"Custom Iterative Ternary Merge Sort" --<www.macscripter.net/t/timsort-and-nigsort/71383/3>
 
set listOfText to words of "now is the time for all good men to come to the aid of the party"
 
-- Sort customiser.
script descendingByLengthThenAscendingLexicographically
on isGreater(a, b)
set lenA to (count a)'s length
set lenB to (count b)'s length
if (lenA = lenB) then return (a > b)
return (alenB > blenA)
else
return (lenB > lenA)
end if
end isGreater
end script
 
set listOfText to words of "now is the time for all good men to come to the aid of the party"
-- Sort the whole list using the above customiser.
tell sorter to ¬
tell sorter to sort(listOfText, 1, -1, {comparer:descendingByLengthThenAscendingLexicographically})
sort(listOfText, 1, -1, {comparer:descendingByLengthThenAscendingLexicographically})
return listOfText</syntaxhighlight>
 
Line 1,626 ⟶ 1,621:
 
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import extensions;
import system'routines;
Line 1,638 ⟶ 1,633:
console.printLine("Descending length: ", items.clone()
.sort::(p,n => p.Length > n.Length).asEnumerable());
console.printLine("Ascending order: ", items.clone()
.sort::(p,n => p.toUpper(invariantLocale) < n.toUpper(invariantLocale)).asEnumerable())
}</syntaxhighlight>
{{out}}
Line 2,015 ⟶ 2,010:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Sort_using_a_custom_comparator}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Sort using a custom comparator 01.png]]
In '''[https://formulae.org/?example=Sort_using_a_custom_comparator this]''' page you can see the program(s) related to this task and their results.
 
[[File:Fōrmulæ - Sort using a custom comparator 02.png]]
 
=={{header|Go}}==
Line 2,218 ⟶ 2,215:
}
}</syntaxhighlight>
 
Using Java 11
<syntaxhighlight lang="java">
import java.util.Comparator;
import java.util.List;
 
public final class SortUsingCustomComparator {
 
public static void main(String[] args) {
List<String> list = List.of( "Here", "are", "some", "sample", "strings", "to", "be", "sorted" );
Comparator<String> custom = Comparator.comparing(String::length, Comparator.reverseOrder())
.thenComparing(Comparator.naturalOrder());
List<String> sortedList = list.stream().sorted(custom).toList();
 
System.out.println(sortedList);
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
[strings, sample, sorted, Here, some, are, be, to]
</pre>
 
=={{header|JavaScript}}==
Line 2,637 ⟶ 2,659:
<pre>Unsorted: [Here, are, some, sample, strings, to, be, sorted]
Sorted: [strings, sample, sorted, Here, some, are, be, to]</pre>
 
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
 
{def sortbylength
 
{def sortbylength.i
{lambda {:x :a}
{if {A.empty? :a}
then {A.new :x}
else {if {> {W.length :x} {W.length {A.first :a}}}
then {A.addfirst! :x :a}
else {A.addfirst! {A.first :a}
{sortbylength.i :x {A.rest :a}}} }}}}
 
{def sortbylength.r
{lambda {:a1 :a2}
{if {A.empty? :a1}
then :a2
else {sortbylength.r {A.rest :a1}
{sortbylength.i {A.first :a1} :a2}} }}}
 
{lambda {:s}
{S.replace (\[|\]) by in
{S.replace , by space in
{A.disp {sortbylength.r {A.new :s} {A.new}} }}}}}
-> sortbylength
 
{sortbylength here are Some sample strings to be sorted}
-> strings sample sorted here Some are to be
</syntaxhighlight>
 
=={{header|Lua}}==
Line 4,145 ⟶ 4,198:
=={{header|Wren}}==
{{libheader|Wren-sort}}
<syntaxhighlight lang="ecmascriptwren">import "./sort" for Cmp, Sort
 
var cmp = Fn.new { |s, t|
Line 4,162 ⟶ 4,215:
Unsorted: [Here, are, some, sample, strings, to, be, sorted]
Sorted : [strings, sample, sorted, Here, some, are, be, to]
</pre>
 
=={{header|Zig}}==
'''Works with:''' 0.11.x, 0.12.0-dev.1390+94cee4fb2
 
For 0.10.x, replace std.mem.sort with std.sort.sort .
 
<syntaxhighlight lang="zig">const std = @import("std");
 
/// Sort by descending length and ascending lexicographical order.
/// If true, element will remain on it's place.
fn lessThanFn(context: void, left: []const u8, right: []const u8) bool {
_ = context;
// Sort by descending length
switch (std.math.order(left.len, right.len)) {
.lt => return false,
.eq => {},
.gt => return true,
}
 
// If length is equal, sort by ascending lexicographical order
return switch (std.ascii.orderIgnoreCase(left, right)) {
.lt => true,
.eq => false,
.gt => false,
};
}
 
pub fn main() void {
var words = [_][]const u8{ "Here", "are", "some", "sample", "strings", "to", "be", "sorted" };
 
std.debug.print("Before: [ ", .{});
for (words) |word| {
std.debug.print("\"{s}\" ", .{word});
}
std.debug.print("]\n", .{});
 
std.mem.sort([]const u8, &words, {}, lessThanFn);
 
std.debug.print("After: [ ", .{});
for (words) |word| {
std.debug.print("\"{s}\" ", .{word});
}
std.debug.print("]\n", .{});
}</syntaxhighlight>
 
{{out}}
<pre>
Before: [ "Here" "are" "some" "sample" "strings" "to" "be" "sorted" ]
After: [ "strings" "sample" "sorted" "Here" "some" "are" "be" "to" ]
</pre>
 
9,476

edits