Sort using a custom comparator: Difference between revisions
Add Zig example
(New post using Java 11 syntax in addition to two existing posts which use Java 5 and Java 8 syntax.) |
(Add Zig example) |
||
Line 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>
|