Taskintro
Sort with a custom key
Also called sort by a key, sort by length, custom sort order, sort with a comparator, sort by two keys.
Sort a list of words by a key of two parts, the length and then the word, and return a new list.
- Evidence
- Code in 10 languages
Task
Sort a list of words by a key of two parts. The function sort_by_length(words) returns the words in ascending order of the length. Words with the same length are in ascending order of their bytes. For example, sort_by_length(["pear", "fig", "apple", "kiwi"]) is ["fig", "kiwi", "pear", "apple"].
Each word has 1 or more lowercase ASCII letters. The list can be empty, and it can have the same word more than once. The function does not change its input, except in C, where the function sorts the array in place.
Solutions
| Language | Sort by the length, then by the word |
|---|---|
| Python | sorted with the key (len(w), w) |
| JavaScript, TypeScript | toSorted with a comparison of the lengths, then of the words |
| Java | sorted with Comparator.comparingInt(String::length).thenComparing(...) |
| C# | OrderBy(w => w.Length).ThenBy(w => w, StringComparer.Ordinal) |
| Go | slices.SortFunc of a copy, with cmp.Or |
| Rust | sort_by_key of a copy, with the key (w.len(), *w) |
| C | qsort with a comparison function |
| C++ | std::ranges::sort with a projection to a std::pair |
| Bash | sort -k1,1n -k2,2 of lines LENGTH WORD in the C locale, then cut |
- A key or a comparison. Python, Rust and C++ give a key for each word. A tuple or a pair compares its first part, then its second part. For Python, "The key corresponding to each item in the list is calculated once and then used for the entire sorting process."1 The other solutions give a comparison of two words, which compares the lengths, then the words.
- The second part of the key. Without it, the order of words with the same length depends on the sort. A stable sort keeps them in input order. An unstable sort can put them in any order.
- The order of the bytes. The words are lowercase ASCII letters, so the order of the bytes is also the alphabetical order. For C#,
StringComparer.Ordinal"performs a case-sensitive ordinal string comparison"2. For Bash, the sort usesLC_ALL=C, so the order does not depend on the locale of the user.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: an empty list gives an empty list.single: one word gives a list with that word.same-length:["dog", "cat", "ant"]gives["ant", "cat", "dog"], from the second part of the key only.duplicates:["b", "a", "b"]gives["a", "b", "b"], with the two words"b"next to each other.sortedandreverse: a list in order and a list in reverse order.long: the lengths 1, 9 and 10 are in ascending order as numbers. As strings, "10" is before "9".prefix:["ab", "a", "abc", "b"]gives["a", "b", "ab", "abc"]. The length comes first, so"b"is before"ab".
Pitfalls
- Python list.sort returns None. "This method modifies the sequence in place for economy of space when sorting a large sequence. To remind users that it operates by side effect, it does not return the sorted sequence"1. Use
sortedfor a new list. Also,key=lenalone keeps pear before kiwi, because "The sort() method is guaranteed to be stable."1
words = ["pear", "fig", "kiwi"]
print(words.sort())
print(words)
print(sorted(["pear", "kiwi", "fig"], key=len))
print(sorted(["pear", "kiwi", "fig"], key=lambda w: (len(w), w)))
None
['fig', 'kiwi', 'pear']
['fig', 'pear', 'kiwi']
['fig', 'kiwi', 'pear']
- JavaScript sort changes the array and compares strings. "The sort() method of Array instances sorts the elements of an array in place and returns the reference to the same array, now sorted."3 In the example,
sorted === wordsistrue. Without a comparison function, "The default sort order is ascending, built upon converting the elements into strings"3, so 10 is before 9. A comparison function "should return a number where: A negative value indicates that a should come before b."3toSorted"returns a new array with the elements sorted in ascending order"4:
const words = ["pear", "fig", "apple", "kiwi"];
const sorted = words.sort((a, b) => a.length - b.length);
console.log(sorted === words, words);
console.log(["ccc", "a", "bb"].toSorted());
console.log([10, 9, 1].toSorted(), [10, 9, 1].toSorted((a, b) => a - b));
true [ 'fig', 'pear', 'kiwi', 'apple' ]
[ 'a', 'bb', 'ccc' ]
[ 1, 10, 9 ] [ 1, 9, 10 ]
- Java a List.of list cannot be sorted in place. For the lists of
List.of, "Calling any mutator method on the List will always cause UnsupportedOperationException to be thrown."5 Sort a copy, or usestream().sorted(...):
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> words = List.of("pear", "fig", "kiwi");
try {
Collections.sort(words);
} catch (UnsupportedOperationException e) {
System.out.println(e.getClass().getSimpleName());
}
List<String> copy = new ArrayList<>(words);
copy.sort(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(copy);
}
}
UnsupportedOperationException
[fig, kiwi, pear]
- C# OrderBy needs ThenBy for the second part. OrderBy "performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved."6 Thus
OrderBy(w => w.Length)keepspearbeforekiwi.ThenByandThenByDescending"enable you to specify additional sort criteria to sort a sequence."6 GiveStringComparer.OrdinaltoThenBy, so that the order of the words does not depend on a culture:
using System;
using System.Linq;
var words = new[] { "pear", "fig", "kiwi" };
Console.WriteLine(string.Join(" ", words.OrderBy(w => w.Length)));
Console.WriteLine(string.Join(" ", words.OrderBy(w => w.Length).ThenBy(w => w, StringComparer.Ordinal)));
Console.WriteLine(string.Compare("a", "b", StringComparison.Ordinal) < 0);
fig pear kiwi
fig kiwi pear
True
- Go SortFunc is not stable. For
slices.SortFunc, "This sort is not guaranteed to be stable."7SortStableFunc"sorts the slice x while keeping the original order of equal elements"7, as in the first line of the example. For a full order, compare the words when the lengths are equal.cmp.Or"returns the first of its arguments that is not equal to the zero value."8
package main
import (
"cmp"
"fmt"
"slices"
"strings"
)
func main() {
words := []string{"pear", "fig", "kiwi", "apple"}
slices.SortStableFunc(words, func(a, b string) int { return cmp.Compare(len(a), len(b)) })
fmt.Println(words)
slices.SortFunc(words, func(a, b string) int {
return cmp.Or(cmp.Compare(len(a), len(b)), strings.Compare(a, b))
})
fmt.Println(words)
}
[fig pear kiwi apple]
[fig kiwi pear apple]
- Rust sort_by with the length only keeps the input order of ties.
sort_byis stable: "This sort is stable (i.e., does not reorder equal elements)"9. Thuspearstays beforekiwi.then_with"Returns self when it’s not Equal. Otherwise calls f and returns the result."10
fn main() {
let mut words = vec!["pear", "fig", "kiwi", "apple"];
words.sort_by(|a, b| a.len().cmp(&b.len()));
println!("{words:?}");
words.sort_by(|a, b| a.len().cmp(&b.len()).then_with(|| a.cmp(b)));
println!("{words:?}");
}
["fig", "pear", "kiwi", "apple"]
["fig", "kiwi", "pear", "apple"]
- C a subtraction of two lengths cannot be negative. The comparison function of
qsort"returns a negative integer value if the first argument is less than the second"11. Butstrlengives asize_t, and "Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer."12 In the example, the length of fig minus the length of pear is greater than 0, so the first line is 1. Compare the lengths with<. Also,qsortgives the function pointers to the items, so each argument is a pointer to aconst char *:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Each item of the array is a const char *, so qsort gives a pointer to it.
static int compare(const void *pa, const void *pb) {
const char *a = *(const char *const *)pa;
const char *b = *(const char *const *)pb;
size_t la = strlen(a);
size_t lb = strlen(b);
if (la != lb) {
return la < lb ? -1 : 1;
}
return strcmp(a, b);
}
int main(void) {
const char *words[] = {"pear", "fig", "kiwi", "apple"};
size_t la = strlen(words[1]);
size_t lb = strlen(words[0]);
printf("%d\n", la - lb > 0);
qsort(words, 4, sizeof words[0], compare);
for (size_t i = 0; i < 4; i++) {
printf("%s%s", i > 0 ? " " : "", words[i]);
}
printf("\n");
return 0;
}
1
fig kiwi pear apple
- C++ std::ranges::sort is not stable. "The order of equivalent elements is not guaranteed to be preserved."13
std::ranges::stable_sortby the length keeps the input order of ties, as in the first line of the example. A projection to a pair of the length and the word gives a full order:
#include <algorithm>
#include <iostream>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
int main() {
std::vector<std::string> words{"pear", "fig", "kiwi", "apple"};
std::ranges::stable_sort(words, {}, [](const std::string &w) { return w.size(); });
for (std::size_t i = 0; i < words.size(); i++) {
std::cout << (i > 0 ? " " : "") << words[i];
}
std::cout << '\n';
std::ranges::sort(words, {}, [](const std::string &w) { return std::pair{w.size(), std::string_view{w}}; });
for (std::size_t i = 0; i < words.size(); i++) {
std::cout << (i > 0 ? " " : "") << words[i];
}
std::cout << '\n';
}
fig pear kiwi apple
fig kiwi pear apple
- Bash sort compares text. Without
-n, the comparisons "shall be performed using the collating sequence of the current locale"14, so 10 is before 9. With-n, sort uses "an initial numeric string"14.-k1,1ngives "a key field that begins at field_start and ends at field_end inclusive"14, so the key is the length only.LC_ALL, if it is set, will "override the values of all the other internationalization variables"14, so the order of the second key does not depend on the locale of the user:
printf '%s\n' 10 9 1 | sort | paste -sd ' ' -
printf '%s\n' 10 9 1 | sort -n | paste -sd ' ' -
printf '%s\n' "4 pear" "3 fig" "4 kiwi" | LC_ALL=C sort -k1,1n -k2,2 | paste -sd ' ' -
1 10 9
1 9 10
3 fig 4 kiwi 4 pear
Related tasks
- Stable sort: keep the input order of items with the same key.
- Comparator: a function that compares two items.
- Decorate, sort, undecorate: calculate the key of each item once.
- Group items by a key: put the words of each length in a group.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-with-a-custom-key/.
def sort_by_length(words: list[str]) -> list[str]:
"""Return the words in order of the length, then of the word."""
# A tuple key compares the length first, then the word.
return sorted(words, key=lambda w: (len(w), w))
test_sort_by_length.py 27 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-with-a-custom-key/.
import pytest
from sort_by_length import sort_by_length
CASES = {
"fruits": (["pear", "fig", "apple", "kiwi"], ["fig", "kiwi", "pear", "apple"]),
"three": (["bb", "a", "ccc"], ["a", "bb", "ccc"]),
"empty": ([], []),
"single": (["x"], ["x"]),
"same-length": (["dog", "cat", "ant"], ["ant", "cat", "dog"]),
"duplicates": (["b", "a", "b"], ["a", "b", "b"]),
"sorted": (["a", "bb", "ccc"], ["a", "bb", "ccc"]),
"reverse": (["ccc", "bb", "a"], ["a", "bb", "ccc"]),
"long": (["abcdefghij", "abcdefghi", "z"], ["z", "abcdefghi", "abcdefghij"]),
"prefix": (["ab", "a", "abc", "b"], ["a", "b", "ab", "abc"]),
}
@pytest.mark.parametrize("name", CASES)
def test_sort_by_length(name):
words, want = CASES[name]
given = list(words)
assert sort_by_length(words) == want
assert words == given
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
#include "sort_by_length.hpp"
#include <algorithm>
#include <string_view>
#include <utility>
std::vector<std::string> sort_by_length(std::vector<std::string> words) {
// The projection gives a key of two parts. A pair compares the first part,
// then the second part.
std::ranges::sort(words, {}, [](const std::string &w) { return std::pair{w.size(), std::string_view{w}}; });
return words;
}
sort_by_length.hpp 10 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
#pragma once
#include <string>
#include <vector>
// sort_by_length returns the words in order of the length, then of the word.
std::vector<std::string> sort_by_length(std::vector<std::string> words);
test_sort_by_length.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
#include "sort_by_length.hpp"
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
static int failures = 0;
using Words = std::vector<std::string>;
static void check(std::string_view name, const Words &words, const Words &want) {
if (sort_by_length(words) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("fruits", Words{"pear", "fig", "apple", "kiwi"}, Words{"fig", "kiwi", "pear", "apple"});
check("three", Words{"bb", "a", "ccc"}, Words{"a", "bb", "ccc"});
check("empty", Words{}, Words{});
check("single", Words{"x"}, Words{"x"});
check("same-length", Words{"dog", "cat", "ant"}, Words{"ant", "cat", "dog"});
check("duplicates", Words{"b", "a", "b"}, Words{"a", "b", "b"});
check("sorted", Words{"a", "bb", "ccc"}, Words{"a", "bb", "ccc"});
check("reverse", Words{"ccc", "bb", "a"}, Words{"a", "bb", "ccc"});
check("long", Words{"abcdefghij", "abcdefghi", "z"}, Words{"z", "abcdefghi", "abcdefghij"});
check("prefix", Words{"ab", "a", "abc", "b"}, Words{"a", "b", "ab", "abc"});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
import java.util.Comparator;
import java.util.List;
final class SortByLength {
private SortByLength() {}
/** Returns the words in order of the length, then of the word. */
static List<String> sortByLength(List<String> words) {
return words.stream()
.sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))
.toList();
}
}
SortByLengthTest.java 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class SortByLengthTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("fruits", List.of("pear", "fig", "apple", "kiwi"), List.of("fig", "kiwi", "pear", "apple")),
Arguments.of("three", List.of("bb", "a", "ccc"), List.of("a", "bb", "ccc")),
Arguments.of("empty", List.of(), List.of()),
Arguments.of("single", List.of("x"), List.of("x")),
Arguments.of("same-length", List.of("dog", "cat", "ant"), List.of("ant", "cat", "dog")),
Arguments.of("duplicates", List.of("b", "a", "b"), List.of("a", "b", "b")),
Arguments.of("sorted", List.of("a", "bb", "ccc"), List.of("a", "bb", "ccc")),
Arguments.of("reverse", List.of("ccc", "bb", "a"), List.of("a", "bb", "ccc")),
Arguments.of("long", List.of("abcdefghij", "abcdefghi", "z"), List.of("z", "abcdefghi", "abcdefghij")),
Arguments.of("prefix", List.of("ab", "a", "abc", "b"), List.of("a", "b", "ab", "abc")));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void sortByLength(String name, List<String> words, List<String> want) {
// List.of gives an unmodifiable list, so the function must not sort in place.
assertEquals(want, SortByLength.sortByLength(words));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
#include "sort_by_length.h"
#include <stdlib.h>
#include <string.h>
// qsort gives the comparison function pointers to two items of the array.
// Each item is a pointer to a word.
static int compare(const void *pa, const void *pb) {
const char *a = *(const char *const *)pa;
const char *b = *(const char *const *)pb;
size_t la = strlen(a);
size_t lb = strlen(b);
if (la != lb) {
// A subtraction of two size_t values cannot be negative.
return la < lb ? -1 : 1;
}
return strcmp(a, b);
}
void sort_by_length(const char **words, size_t n) {
if (n > 1) {
qsort(words, n, sizeof words[0], compare);
}
}
sort_by_length.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
#ifndef SORT_BY_LENGTH_H
#define SORT_BY_LENGTH_H
#include <stddef.h>
// sort_by_length sorts the n words in place: in order of the length, then of
// the bytes of the word.
void sort_by_length(const char **words, size_t n);
#endif
test_sort_by_length.c 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
#include "sort_by_length.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
#define L(...) {__VA_ARGS__}
// An empty list has "" in it, because C has no empty array. N gives the real
// length.
#define CHECK(name, n, given, sorted) \
do { \
const char *g[] = given; \
const char *const want[] = sorted; \
const size_t have_n = n; \
sort_by_length(g, have_n); \
int ok = 1; \
for (size_t i = 0; ok && i < have_n; i++) { \
ok = strcmp(g[i], want[i]) == 0; \
} \
if (!ok) { \
fprintf(stderr, "case %s failed\n", name); \
failures++; \
} \
} while (0)
int main(void) {
CHECK("fruits", 4, L("pear", "fig", "apple", "kiwi"), L("fig", "kiwi", "pear", "apple"));
CHECK("three", 3, L("bb", "a", "ccc"), L("a", "bb", "ccc"));
CHECK("empty", 0, L(""), L(""));
CHECK("single", 1, L("x"), L("x"));
CHECK("same-length", 3, L("dog", "cat", "ant"), L("ant", "cat", "dog"));
CHECK("duplicates", 3, L("b", "a", "b"), L("a", "b", "b"));
CHECK("sorted", 3, L("a", "bb", "ccc"), L("a", "bb", "ccc"));
CHECK("reverse", 3, L("ccc", "bb", "a"), L("a", "bb", "ccc"));
CHECK("long", 3, L("abcdefghij", "abcdefghi", "z"), L("z", "abcdefghi", "abcdefghij"));
CHECK("prefix", 4, L("ab", "a", "abc", "b"), L("a", "b", "ab", "abc"));
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
using System;
using System.Linq;
public static class SortByLength
{
// Sort returns the words in order of the length, then of the word.
public static string[] Sort(string[] words)
{
// StringComparer.Ordinal compares the code units, not the rules of a culture.
return words.OrderBy(w => w.Length).ThenBy(w => w, StringComparer.Ordinal).ToArray();
}
}
SortByLengthTests.cs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
using Xunit;
public sealed class SortByLengthTests
{
public static TheoryData<string, string[], string[]> Cases => new()
{
{ "fruits", new string[] { "pear", "fig", "apple", "kiwi" }, new string[] { "fig", "kiwi", "pear", "apple" } },
{ "three", new string[] { "bb", "a", "ccc" }, new string[] { "a", "bb", "ccc" } },
{ "empty", new string[0], new string[0] },
{ "single", new string[] { "x" }, new string[] { "x" } },
{ "same-length", new string[] { "dog", "cat", "ant" }, new string[] { "ant", "cat", "dog" } },
{ "duplicates", new string[] { "b", "a", "b" }, new string[] { "a", "b", "b" } },
{ "sorted", new string[] { "a", "bb", "ccc" }, new string[] { "a", "bb", "ccc" } },
{ "reverse", new string[] { "ccc", "bb", "a" }, new string[] { "a", "bb", "ccc" } },
{ "long", new string[] { "abcdefghij", "abcdefghi", "z" }, new string[] { "z", "abcdefghi", "abcdefghij" } },
{ "prefix", new string[] { "ab", "a", "abc", "b" }, new string[] { "a", "b", "ab", "abc" } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string[] words, string[] want)
{
Assert.NotNull(name);
var given = (string[])words.Clone();
Assert.Equal(want, SortByLength.Sort(words));
Assert.Equal(given, words);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
/**
* @param {string[]} words
* @returns {string[]}
*/
export function sortByLength(words) {
// toSorted returns a new array. The comparison gives a negative number, 0 or
// a positive number: the length first, then the code units of the words.
return words.toSorted((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
}
sort_by_length.test.js 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { sortByLength } from "./sort_by_length.js";
const cases = [
["fruits", ["pear", "fig", "apple", "kiwi"], ["fig", "kiwi", "pear", "apple"]],
["three", ["bb", "a", "ccc"], ["a", "bb", "ccc"]],
["empty", [], []],
["single", ["x"], ["x"]],
["same-length", ["dog", "cat", "ant"], ["ant", "cat", "dog"]],
["duplicates", ["b", "a", "b"], ["a", "b", "b"]],
["sorted", ["a", "bb", "ccc"], ["a", "bb", "ccc"]],
["reverse", ["ccc", "bb", "a"], ["a", "bb", "ccc"]],
["long", ["abcdefghij", "abcdefghi", "z"], ["z", "abcdefghi", "abcdefghij"]],
["prefix", ["ab", "a", "abc", "b"], ["a", "b", "ab", "abc"]],
];
for (const [name, words, want] of cases) {
test(name, () => {
const given = [...words];
assert.deepEqual(sortByLength(words), want);
assert.deepEqual(words, given);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
export function sortByLength(words: readonly string[]): string[] {
// toSorted returns a new array. The comparison gives a negative number, 0 or
// a positive number: the length first, then the code units of the words.
return words.toSorted((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
}
sort_by_length.test.ts 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { sortByLength } from "./sort_by_length.ts";
const cases: [string, string[], string[]][] = [
["fruits", ["pear", "fig", "apple", "kiwi"], ["fig", "kiwi", "pear", "apple"]],
["three", ["bb", "a", "ccc"], ["a", "bb", "ccc"]],
["empty", [], []],
["single", ["x"], ["x"]],
["same-length", ["dog", "cat", "ant"], ["ant", "cat", "dog"]],
["duplicates", ["b", "a", "b"], ["a", "b", "b"]],
["sorted", ["a", "bb", "ccc"], ["a", "bb", "ccc"]],
["reverse", ["ccc", "bb", "a"], ["a", "bb", "ccc"]],
["long", ["abcdefghij", "abcdefghi", "z"], ["z", "abcdefghi", "abcdefghij"]],
["prefix", ["ab", "a", "abc", "b"], ["a", "b", "ab", "abc"]],
];
for (const [name, words, want] of cases) {
test(name, () => {
const given = [...words];
assert.deepEqual(sortByLength(words), want);
assert.deepEqual(words, given);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
// Package sortbylength sorts words by their length, then by the word.
package sortbylength
import (
"cmp"
"slices"
"strings"
)
// SortByLength returns a sorted copy of words: in order of the length, then
// of the bytes of the word.
func SortByLength(words []string) []string {
out := slices.Clone(words)
slices.SortFunc(out, func(a, b string) int {
// cmp.Or gives the first result that is not 0.
return cmp.Or(cmp.Compare(len(a), len(b)), strings.Compare(a, b))
})
return out
}
sort_by_length_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
package sortbylength
import (
"slices"
"testing"
)
var cases = []struct {
name string
words []string
want []string
}{
{"fruits", []string{"pear", "fig", "apple", "kiwi"}, []string{"fig", "kiwi", "pear", "apple"}},
{"three", []string{"bb", "a", "ccc"}, []string{"a", "bb", "ccc"}},
{"empty", []string{}, []string{}},
{"single", []string{"x"}, []string{"x"}},
{"same-length", []string{"dog", "cat", "ant"}, []string{"ant", "cat", "dog"}},
{"duplicates", []string{"b", "a", "b"}, []string{"a", "b", "b"}},
{"sorted", []string{"a", "bb", "ccc"}, []string{"a", "bb", "ccc"}},
{"reverse", []string{"ccc", "bb", "a"}, []string{"a", "bb", "ccc"}},
{"long", []string{"abcdefghij", "abcdefghi", "z"}, []string{"z", "abcdefghi", "abcdefghij"}},
{"prefix", []string{"ab", "a", "abc", "b"}, []string{"a", "b", "ab", "abc"}},
}
func TestSortByLength(t *testing.T) {
for _, c := range cases {
given := slices.Clone(c.words)
if got := SortByLength(c.words); !slices.Equal(got, c.want) {
t.Errorf("%s: got %q, want %q", c.name, got, c.want)
}
if !slices.Equal(c.words, given) {
t.Errorf("%s: the input changed to %q", c.name, c.words)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
/// Returns the words in order of the length, then of the word.
pub fn sort_by_length<'a>(words: &[&'a str]) -> Vec<&'a str> {
let mut out = words.to_vec();
// A tuple key compares the length first, then the word.
out.sort_by_key(|w| (w.len(), *w));
out
}
tests/sort_by_length_test.rs 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-with-a-custom-key/.
use algo_sort_with_a_custom_key::sort_by_length;
#[test]
fn cases() {
let cases: Vec<(&str, &[&str], Vec<&str>)> = vec![
("fruits", &["pear", "fig", "apple", "kiwi"], vec!["fig", "kiwi", "pear", "apple"]),
("three", &["bb", "a", "ccc"], vec!["a", "bb", "ccc"]),
("empty", &[], Vec::<&str>::new()),
("single", &["x"], vec!["x"]),
("same-length", &["dog", "cat", "ant"], vec!["ant", "cat", "dog"]),
("duplicates", &["b", "a", "b"], vec!["a", "b", "b"]),
("sorted", &["a", "bb", "ccc"], vec!["a", "bb", "ccc"]),
("reverse", &["ccc", "bb", "a"], vec!["a", "bb", "ccc"]),
("long", &["abcdefghij", "abcdefghi", "z"], vec!["z", "abcdefghi", "abcdefghij"]),
("prefix", &["ab", "a", "abc", "b"], vec!["a", "b", "ab", "abc"]),
];
for (name, words, want) in cases {
assert_eq!(sort_by_length(words), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-with-a-custom-key/.
# sort_by_length WORD...
# Prints the words, one on each line, in order of the length, then of the bytes
# of the word.
sort_by_length() {
local w
for w in "$@"; do
printf '%s %s\n' "${#w}" "$w"
done | LC_ALL=C sort -k1,1n -k2,2 | cut -d' ' -f2-
}
test_sort_by_length.bats 30 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-with-a-custom-key/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/sort_by_length.sh"
}
check() { # check WANT WORD...
local want got
# %b turns each \n in WANT into a newline. The x keeps the trailing
# newlines, which $(...) removes.
want=$(printf '%b' "$1"; printf x)
shift
got=$(sort_by_length "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "fruits" { check "fig\nkiwi\npear\napple\n" pear fig apple kiwi; }
@test "three" { check "a\nbb\nccc\n" bb a ccc; }
@test "empty" { check ""; }
@test "single" { check "x\n" x; }
@test "same-length" { check "ant\ncat\ndog\n" dog cat ant; }
@test "duplicates" { check "a\nb\nb\n" b a b; }
@test "sorted" { check "a\nbb\nccc\n" a bb ccc; }
@test "reverse" { check "a\nbb\nccc\n" ccc bb a; }
@test "long" { check "z\nabcdefghi\nabcdefghij\n" abcdefghij abcdefghi z; }
@test "prefix" { check "a\nb\nab\nabc\n" ab a abc b; }
References
- The Python Standard Library, Built-in Types, list.sort()
- .NET API reference, StringComparer.Ordinal property, Definition
- MDN Web Docs, Array.prototype.sort(), Description; Parameters
- MDN Web Docs, Array.prototype.toSorted(), Description
- Java SE 25 API, Interface List, Unmodifiable Lists
- .NET API reference, Enumerable.OrderBy method, Remarks
- Go standard library, package slices, func SortFunc; func SortStableFunc
- Go standard library, package cmp, func Or
- Rust standard library, primitive type slice, sort_by; sort_by_key
- Rust standard library, enum Ordering, then_with
- cppreference.com, qsort (C), Parameters
- cppreference.com, Arithmetic operators (C), Overflows
- cppreference.com, std::ranges::sort, Description
- The Open Group Base Specifications Issue 8, sort, DESCRIPTION; OPTIONS
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag D7CMAP Edit this page History Report an error Markdown