How to resolve the algorithm Sort using a custom comparator step by step in the Zig programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sort using a custom comparator step by step in the Zig programming language
Table of Contents
Problem Statement
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sort using a custom comparator step by step in the Zig programming language
Source code in the zig programming language
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", .{});
}
You may also check:How to resolve the algorithm Calendar step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Sum and product of an array step by step in the V programming language
You may also check:How to resolve the algorithm Range extraction step by step in the J programming language
You may also check:How to resolve the algorithm Hofstadter Q sequence step by step in the Visual FoxPro programming language
You may also check:How to resolve the algorithm Gray code step by step in the BASIC programming language