Programming Search⌘K

Taskcore

Sort a list of records

Also called sort objects by a field, sort by multiple keys, sort structs, stable sort by key.

Sort a list of records by one field, then by a second field in the opposite direction, with a stable sort so that records with equal keys keep their input order.

Task

Sort a list of employee records. Each record has a name, a department and a salary. Sort by department in ascending order. In one department, sort by salary from high to low. If two records have the same department and the same salary, keep them in their input order. A sort that does this is a stable sort.

Compare the department names by their characters, not by the rules of a language. So "Sales" comes before "eng", because S (U+0053) is before e (U+0065). The order must be the same on every machine. A sort for people to read is a different job. The section on locales below shows it.

The salaries are integers that fit in 32 bits, and they can be negative. The names contain no tab or newline. They contain only characters below U+D800, so the byte order of UTF-8, the code unit order of UTF-16 and the code point order are the same.

Solutions

Each solution gives the sort one comparison of two keys. The first key is the department. If the departments are equal, the second key is the salary, in reverse.

  • Python. sorted(employees, key=lambda e: (e.dept, -e.salary)). Tuples compare item by item, and strings compare by code point. -e.salary puts high salaries first. Python sorts are always stable.
  • JavaScript and TypeScript. toSorted with a comparison that uses < and > on the department, then b.salary - a.salary. The || operator goes to the second key only when the first comparison gives 0. The standard requires a stable sort, and < compares UTF-16 code units, so the result does not depend on the locale. The subtraction is safe here, because the numbers are doubles and the salaries are small.
  • Java. Comparator.comparing(Employee::dept).thenComparing(Comparator.comparingInt(Employee::salary).reversed()) on stream().sorted(...). For an ordered stream, sorted is stable. String.compareTo compares UTF-16 values and does not use the locale.
  • C#. OrderBy(e => e.Dept, StringComparer.Ordinal).ThenByDescending(e => e.Salary). OrderBy is a stable sort. Give StringComparer.Ordinal, because the default comparer of strings uses the current culture.
  • Go. slices.SortStableFunc on a copy, with cmp.Or(strings.Compare(a.Dept, b.Dept), cmp.Compare(b.Salary, a.Salary)). cmp.Or returns the first value that is not 0. Go compares strings byte by byte.
  • Rust. sort_by with a.dept.cmp(&b.dept).then_with(|| b.salary.cmp(&a.salary)). sort_by is stable. sort_unstable_by is not.
  • C++. std::ranges::stable_sort with std::tie(a.dept, b.salary) < std::tie(b.dept, a.salary). The salaries change sides, so high salaries come first. std::string compares each char as unsigned char, so UTF-8 sorts by code point.
  • C. qsort does not keep equal elements in order. So the code copies each record with its input position into a new array, and uses the position as the last key. The comparison uses strcmp, which compares bytes as unsigned char, and (x > y) - (x < y) for the numbers.
  • Bash. LC_ALL=C sort -s -t $'\t' -k2,2 -k3,3nr on lines of tab-separated fields. -k2,2 is field 2 only. -k3,3nr is field 3 as a number, in reverse. -s keeps the input order of equal keys. LC_ALL=C compares bytes on every machine.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty and single: the result is the input.
  • sorted and reversed: input that is already in order, and input in the reverse order.
  • ties: three records with the same department and salary, with other records between them. They must keep their input order.
  • many-ties: 40 records with two departments in turn and the same salary. An unstable sort can change their order. On a short list, an unstable sort often gives the stable order by chance, so this case is long.
  • case: "Sales" sorts before "eng" in code point order.
  • non-ascii: "équipe" sorts after "zoo", because U+00E9 is after z.
  • negative: 5, 0 and -5 sort as numbers, high to low.
  • overflow: the salaries 2000000000 and -2000000000. Their difference does not fit in 32 bits.

Pitfalls

  • Reversing the result instead of the comparison. A reversed ascending sort is in descending order, but it also reverses the order of equal keys. Python reverse=True keeps equal keys in their input order:

This code runs but gives a wrong answer on purpose.

staff = [("Zoe", 100), ("Al", 100), ("Bo", 90)]
print(sorted(staff, key=lambda e: e[1])[::-1])
Output
[('Al', 100), ('Zoe', 100), ('Bo', 90)]
staff = [("Zoe", 100), ("Al", 100), ("Bo", 90)]
print(sorted(staff, key=lambda e: e[1], reverse=True))
Output
[('Zoe', 100), ('Al', 100), ('Bo', 90)]
  • The default sort of JavaScript compares strings. With no comparison function, sort changes each value to a string first:

This code runs but gives a wrong answer on purpose.

console.log([100, 90, 1000].sort());
Output
[ 100, 1000, 90 ]
console.log([100, 90, 1000].sort((a, b) => a - b));
Output
[ 90, 100, 1000 ]
  • Subtraction in a comparison of 32-bit integers. b - a can overflow. In Java the result keeps only the low-order bits, so its sign is wrong, and the order is wrong. Use Integer.compare, Comparator.comparingInt, cmp.Compare or (x > y) - (x < y):

This code runs but gives a wrong answer on purpose.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> salaries = new ArrayList<>(List.of(-2_000_000_000, 2_000_000_000, 0));
        salaries.sort((a, b) -> b - a); // high to low, but b - a overflows
        System.out.println(salaries);
    }
}
Output
[-2000000000, 2000000000, 0]
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> salaries = new ArrayList<>(List.of(-2_000_000_000, 2_000_000_000, 0));
        salaries.sort((a, b) -> Integer.compare(b, a));
        System.out.println(salaries);
    }
}
Output
[2000000000, 0, -2000000000]
  • Code unit order is not code point order. A character above U+FFFF is two UTF-16 code units, and the first unit is in the range D800 to DBFF. So JavaScript, Java and C# Ordinal put U+1F600 before U+FF5E. Python, Go, Rust, C and C++ compare code points or UTF-8 bytes, and they put U+FF5E first:
const hex = (s) => "U+" + s.codePointAt(0).toString(16).toUpperCase();
console.log(["\u{FF5E}", "\u{1F600}"].sort().map(hex));
Output
[ 'U+1F600', 'U+FF5E' ]
print([f"U+{ord(s):04X}" for s in sorted(["\uFF5E", "\U0001F600"])])
Output
['U+FF5E', 'U+1F600']
  • An order for people is a different sort. Code point order puts all capital letters before all small letters, and it puts é after z. To sort names for people to read, use the collation rules of a locale. Intl.Collator in JavaScript and java.text.Collator in Java do this:
const depts = ["eng", "Sales", "équipe", "ops"];
console.log(depts.toSorted());
console.log(depts.toSorted(new Intl.Collator("en").compare));
Output
[ 'Sales', 'eng', 'ops', 'équipe' ]
[ 'eng', 'équipe', 'ops', 'Sales' ]

The rules change from one language to the next. In Swedish, å, ä and ö come after z. In Danish, aa sorts as å, at the end of the alphabet. The cases in cases/locale.jsonl test this for the JavaScript, TypeScript and Java solutions, because their results do not depend on the machine. Official Node.js binaries include all of the ICU data, and the JDK supplies its own RuleBasedCollator. On Linux, .NET gets its collation rules from the ICU library of the system, so the result of a culture comparison can change from one machine to the next.

  • A default comparer that uses the culture. In C#, OrderBy(e => e.Dept) with no comparer, List<string>.Sort() and string.CompareTo use the current culture. So the same program can give a different order on a different machine. Give StringComparer.Ordinal for a fixed order, or a culture-specific comparer for an order that people read. Also, List<T>.Sort is not stable.

  • A sort by two passes in the wrong order. With a stable sort you can sort by the second key first, then by the first key. The last sort is the main key. If you sort by department first and then by salary, the result is ordered by salary.

  • The last comparison of sort. GNU sort compares the whole lines when all the keys are equal. So without -s, records with equal keys come out in the order of their names, not in their input order. POSIX does not define -s, but its rationale says that a stable option is usually -s. With -k2, the key goes to the end of the line. Write -k2,2 for one field.

Code

The build runs the native tests of each language in a pinned toolchain.

sort_employees.pyI0tests passRawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-a-list-of-records/.

from collections.abc import Iterable
from dataclasses import dataclass


@dataclass(frozen=True)
class Employee:
    name: str
    dept: str
    salary: int


def sort_employees(employees: Iterable[Employee]) -> list[Employee]:
    """Return the records by dept, then by salary from high to low.

    The sort is stable, so records with equal keys keep their input order.
    """
    # The key is a tuple: tuples compare item by item. -salary puts high first.
    return sorted(employees, key=lambda e: (e.dept, -e.salary))
test_sort_employees.py 82 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-a-list-of-records/.

import pytest

from sort_employees import Employee, sort_employees

# The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
MANY = [(f"n{i + 1:02d}", "a" if i % 2 else "b", 1) for i in range(40)]

CASES = {
    "mixed": (
        [
            ("Ada", "eng", 120),
            ("Bob", "sales", 90),
            ("Cy", "eng", 150),
            ("Di", "ops", 100),
        ],
        [
            ("Cy", "eng", 150),
            ("Ada", "eng", 120),
            ("Di", "ops", 100),
            ("Bob", "sales", 90),
        ],
    ),
    "same-salary-other-dept": (
        [("Ann", "ops", 100), ("Ben", "eng", 100), ("Cat", "hr", 100)],
        [("Ben", "eng", 100), ("Cat", "hr", 100), ("Ann", "ops", 100)],
    ),
    "empty": ([], []),
    "single": ([("Ada", "eng", 120)], [("Ada", "eng", 120)]),
    "sorted": (
        [("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)],
        [("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)],
    ),
    "reversed": (
        [("Bob", "ops", 90), ("Ada", "eng", 120), ("Cy", "eng", 150)],
        [("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)],
    ),
    "ties": (
        [
            ("Zoe", "eng", 100),
            ("Xi", "hr", 80),
            ("Al", "eng", 100),
            ("Yu", "hr", 80),
            ("Mo", "eng", 100),
        ],
        [
            ("Zoe", "eng", 100),
            ("Al", "eng", 100),
            ("Mo", "eng", 100),
            ("Xi", "hr", 80),
            ("Yu", "hr", 80),
        ],
    ),
    "many-ties": (MANY, MANY[1::2] + MANY[0::2]),
    "case": (
        [("Ann", "eng", 100), ("Bea", "Sales", 90), ("Cal", "ops", 80)],
        [("Bea", "Sales", 90), ("Ann", "eng", 100), ("Cal", "ops", 80)],
    ),
    "non-ascii": (
        [("Eve", "équipe", 100), ("Fay", "zoo", 90), ("Gus", "eng", 80)],
        [("Gus", "eng", 80), ("Fay", "zoo", 90), ("Eve", "équipe", 100)],
    ),
    "negative": (
        [("Hal", "eng", 0), ("Ida", "eng", -5), ("Jo", "eng", 5)],
        [("Jo", "eng", 5), ("Hal", "eng", 0), ("Ida", "eng", -5)],
    ),
    "overflow": (
        [("Kim", "eng", -2000000000), ("Lee", "eng", 2000000000)],
        [("Lee", "eng", 2000000000), ("Kim", "eng", -2000000000)],
    ),
}


@pytest.mark.parametrize("name", CASES)
def test_cases(name: str) -> None:
    given, want = CASES[name]
    employees = [Employee(*e) for e in given]
    got = sort_employees(employees)
    assert got == [Employee(*e) for e in want]
    assert employees == [Employee(*e) for e in given], "the input must not change"
sort_employees.cppI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

#include "sort_employees.hpp"

#include <algorithm>
#include <tuple>

void sort_employees(std::vector<Employee>& employees) {
    // std::sort is not stable. std::ranges::stable_sort is.
    std::ranges::stable_sort(employees, [](const Employee& a, const Employee& b) {
        // std::tie compares the items in turn. b.salary is on the left, so high comes first.
        // std::string compares chars as unsigned char, so UTF-8 text sorts by code point.
        return std::tie(a.dept, b.salary) < std::tie(b.dept, a.salary);
    });
}
sort_employees.hpp 18 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

#pragma once

#include <string>
#include <vector>

struct Employee {
    std::string name;
    std::string dept;
    long salary;  // long has at least 32 bits
    bool operator==(const Employee&) const = default;
};

// Sorts the records in place by dept, then by salary from high to low.
// Records with equal keys keep their input order.
void sort_employees(std::vector<Employee>& employees);
test_sort_employees.cpp 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

#include "sort_employees.hpp"

#include <cstdio>
#include <format>
#include <string>
#include <vector>

namespace {

using List = std::vector<Employee>;

int failures = 0;

void check(const char* name, List given, const List& want) {
    sort_employees(given);
    if (given != want) {
        std::printf("FAIL %s\n", name);
        ++failures;
    } else {
        std::printf("ok %s\n", name);
    }
}

// The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
// With parity 0 or 1, only the records at even or odd positions.
List many(int parity) {
    List out;
    for (int i = 0; i < 40; ++i) {
        if (parity >= 0 && i % 2 != parity) continue;
        out.push_back({std::format("n{:02}", i + 1), i % 2 == 1 ? "a" : "b", 1});
    }
    return out;
}

}  // namespace

int main() {
    check("mixed", {{"Ada", "eng", 120}, {"Bob", "sales", 90}, {"Cy", "eng", 150}, {"Di", "ops", 100}},
          {{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Di", "ops", 100}, {"Bob", "sales", 90}});
    check("same-salary-other-dept", {{"Ann", "ops", 100}, {"Ben", "eng", 100}, {"Cat", "hr", 100}},
          {{"Ben", "eng", 100}, {"Cat", "hr", 100}, {"Ann", "ops", 100}});
    check("empty", {}, {});
    check("single", {{"Ada", "eng", 120}}, {{"Ada", "eng", 120}});
    check("sorted", {{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}},
          {{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}});
    check("reversed", {{"Bob", "ops", 90}, {"Ada", "eng", 120}, {"Cy", "eng", 150}},
          {{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}});
    check("ties", {{"Zoe", "eng", 100}, {"Xi", "hr", 80}, {"Al", "eng", 100}, {"Yu", "hr", 80}, {"Mo", "eng", 100}},
          {{"Zoe", "eng", 100}, {"Al", "eng", 100}, {"Mo", "eng", 100}, {"Xi", "hr", 80}, {"Yu", "hr", 80}});
    List many_want = many(1);
    many_want.append_range(many(0));
    check("many-ties", many(-1), many_want);
    check("case", {{"Ann", "eng", 100}, {"Bea", "Sales", 90}, {"Cal", "ops", 80}},
          {{"Bea", "Sales", 90}, {"Ann", "eng", 100}, {"Cal", "ops", 80}});
    check("non-ascii", {{"Eve", "équipe", 100}, {"Fay", "zoo", 90}, {"Gus", "eng", 80}},
          {{"Gus", "eng", 80}, {"Fay", "zoo", 90}, {"Eve", "équipe", 100}});
    check("negative", {{"Hal", "eng", 0}, {"Ida", "eng", -5}, {"Jo", "eng", 5}},
          {{"Jo", "eng", 5}, {"Hal", "eng", 0}, {"Ida", "eng", -5}});
    check("overflow", {{"Kim", "eng", -2000000000}, {"Lee", "eng", 2000000000}},
          {{"Lee", "eng", 2000000000}, {"Kim", "eng", -2000000000}});
    return failures == 0 ? 0 : 1;
}
SortEmployees.javaI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

import java.text.Collator;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

/** Sorts records of employees. */
public final class SortEmployees {

  /** An employee record. */
  public record Employee(String name, String dept, int salary) {}

  /** By dept, then by salary from high to low. comparingInt does not subtract, so it cannot overflow. */
  static final Comparator<Employee> BY_DEPT_THEN_SALARY_DESC =
      Comparator.comparing(Employee::dept)
          .thenComparing(Comparator.comparingInt(Employee::salary).reversed());

  private SortEmployees() {}

  /**
   * Returns a new list of the records by dept, then by salary from high to low. The sort is
   * stable, so records with equal keys keep their input order.
   */
  public static List<Employee> sortEmployees(List<Employee> employees) {
    // String.compareTo compares UTF-16 code units, the same for every locale.
    return employees.stream().sorted(BY_DEPT_THEN_SALARY_DESC).toList();
  }

  /** Returns a new list of the names in the order of the collation rules of a locale, such as "sv". */
  public static List<String> sortNames(List<String> names, String locale) {
    Collator collator = Collator.getInstance(Locale.forLanguageTag(locale));
    return names.stream().sorted(collator).toList();
  }
}
SortEmployeesTest.java 98 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
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 SortEmployeesTest {

  private static SortEmployees.Employee e(String name, String dept, int salary) {
    return new SortEmployees.Employee(name, dept, salary);
  }

  /** The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1. */
  private static List<SortEmployees.Employee> many(int parity) {
    return IntStream.range(0, 40)
        .filter(i -> parity < 0 || i % 2 == parity)
        .mapToObj(i -> e("n%02d".formatted(i + 1), i % 2 == 1 ? "a" : "b", 1))
        .toList();
  }

  static Stream<Arguments> cases() {
    List<SortEmployees.Employee> manyWant = new ArrayList<>(many(1));
    manyWant.addAll(many(0));
    return Stream.of(
        Arguments.of(
            "mixed",
            List.of(e("Ada", "eng", 120), e("Bob", "sales", 90), e("Cy", "eng", 150), e("Di", "ops", 100)),
            List.of(e("Cy", "eng", 150), e("Ada", "eng", 120), e("Di", "ops", 100), e("Bob", "sales", 90))),
        Arguments.of(
            "same-salary-other-dept",
            List.of(e("Ann", "ops", 100), e("Ben", "eng", 100), e("Cat", "hr", 100)),
            List.of(e("Ben", "eng", 100), e("Cat", "hr", 100), e("Ann", "ops", 100))),
        Arguments.of("empty", List.of(), List.of()),
        Arguments.of("single", List.of(e("Ada", "eng", 120)), List.of(e("Ada", "eng", 120))),
        Arguments.of(
            "sorted",
            List.of(e("Cy", "eng", 150), e("Ada", "eng", 120), e("Bob", "ops", 90)),
            List.of(e("Cy", "eng", 150), e("Ada", "eng", 120), e("Bob", "ops", 90))),
        Arguments.of(
            "reversed",
            List.of(e("Bob", "ops", 90), e("Ada", "eng", 120), e("Cy", "eng", 150)),
            List.of(e("Cy", "eng", 150), e("Ada", "eng", 120), e("Bob", "ops", 90))),
        Arguments.of(
            "ties",
            List.of(e("Zoe", "eng", 100), e("Xi", "hr", 80), e("Al", "eng", 100), e("Yu", "hr", 80), e("Mo", "eng", 100)),
            List.of(e("Zoe", "eng", 100), e("Al", "eng", 100), e("Mo", "eng", 100), e("Xi", "hr", 80), e("Yu", "hr", 80))),
        Arguments.of("many-ties", many(-1), manyWant),
        Arguments.of(
            "case",
            List.of(e("Ann", "eng", 100), e("Bea", "Sales", 90), e("Cal", "ops", 80)),
            List.of(e("Bea", "Sales", 90), e("Ann", "eng", 100), e("Cal", "ops", 80))),
        Arguments.of(
            "non-ascii",
            List.of(e("Eve", "équipe", 100), e("Fay", "zoo", 90), e("Gus", "eng", 80)),
            List.of(e("Gus", "eng", 80), e("Fay", "zoo", 90), e("Eve", "équipe", 100))),
        Arguments.of(
            "negative",
            List.of(e("Hal", "eng", 0), e("Ida", "eng", -5), e("Jo", "eng", 5)),
            List.of(e("Jo", "eng", 5), e("Hal", "eng", 0), e("Ida", "eng", -5))),
        Arguments.of(
            "overflow",
            List.of(e("Kim", "eng", -2000000000), e("Lee", "eng", 2000000000)),
            List.of(e("Lee", "eng", 2000000000), e("Kim", "eng", -2000000000))));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void sortsByDeptThenSalaryDescending(
      String name, List<SortEmployees.Employee> given, List<SortEmployees.Employee> want) {
    assertEquals(want, SortEmployees.sortEmployees(given), name);
  }

  /** The cases of cases/locale.jsonl. */
  static Stream<Arguments> locales() {
    return Stream.of(
        Arguments.of("en-accents", "en", List.of("zebra", "Émile", "apple", "Eve", "eagle"), List.of("apple", "eagle", "Émile", "Eve", "zebra")),
        Arguments.of("en-case", "en", List.of("b", "B", "a", "A"), List.of("a", "A", "b", "B")),
        Arguments.of("en-accent-order", "en", List.of("resume", "résumé", "Resume", "rèsume"), List.of("resume", "Resume", "résumé", "rèsume")),
        Arguments.of("sv-letters", "sv", List.of("ö", "z", "o", "a", "å", "ä"), List.of("a", "o", "z", "å", "ä", "ö")),
        Arguments.of("sv-names", "sv", List.of("Örjan", "Zara", "Olof", "Åsa", "Anna", "Ärla"), List.of("Anna", "Olof", "Zara", "Åsa", "Ärla", "Örjan")),
        Arguments.of("de-umlaut", "de", List.of("Äpfel", "Zebra", "Apfel", "apfel"), List.of("apfel", "Apfel", "Äpfel", "Zebra")),
        Arguments.of("da-aa", "da", List.of("Aase", "Zelda", "Ågot", "Øjvind", "Ærø"), List.of("Zelda", "Ærø", "Øjvind", "Ågot", "Aase")),
        Arguments.of("es-enye", "es", List.of("llama", "luz", "lzx", "ñu", "nube", "oso"), List.of("llama", "luz", "lzx", "nube", "ñu", "oso")));
  }

  @ParameterizedTest(name = "locale {0}")
  @MethodSource("locales")
  void sortsNamesByLocale(String name, String locale, List<String> names, List<String> want) {
    assertEquals(want, SortEmployees.sortNames(names, locale), name);
  }
}
sort_employees.cI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

#include "sort_employees.h"

#include <stdlib.h>
#include <string.h>

// qsort is not stable, so each record keeps its input position as the last key.
struct ranked {
    struct employee e;
    size_t pos;
};

static int compare(const void *pa, const void *pb) {
    const struct ranked *a = pa, *b = pb;
    // strcmp compares bytes as unsigned char, so UTF-8 text sorts by code point.
    int c = strcmp(a->e.dept, b->e.dept);
    if (c != 0) {
        return c;
    }
    // Not b - a: that can overflow. Here b comes first, so high salaries come first.
    if (a->e.salary != b->e.salary) {
        return (b->e.salary > a->e.salary) - (b->e.salary < a->e.salary);
    }
    return (a->pos > b->pos) - (a->pos < b->pos);
}

int sort_employees(struct employee *employees, size_t n) {
    if (n < 2) {
        return 0;
    }
    struct ranked *r = malloc(n * sizeof *r);
    if (r == NULL) {
        return -1;
    }
    for (size_t i = 0; i < n; i++) {
        r[i] = (struct ranked){employees[i], i};
    }
    qsort(r, n, sizeof *r, compare);
    for (size_t i = 0; i < n; i++) {
        employees[i] = r[i].e;
    }
    free(r);
    return 0;
}
sort_employees.h 20 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

#ifndef SORT_EMPLOYEES_H
#define SORT_EMPLOYEES_H

#include <stddef.h>

struct employee {
    const char *name;
    const char *dept;  // UTF-8
    long salary;       // long has at least 32 bits
};

// sort_employees sorts the n records in place by dept, then by salary from
// high to low. Records with equal keys keep their input order. It returns 0,
// or -1 if it cannot get memory; then the records do not change.
int sort_employees(struct employee *employees, size_t n);

#endif
test_sort_employees.c 88 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

#include "sort_employees.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static int same(const struct employee *a, const struct employee *b, size_t n) {
    for (size_t i = 0; i < n; i++) {
        if (strcmp(a[i].name, b[i].name) != 0 || strcmp(a[i].dept, b[i].dept) != 0 ||
            a[i].salary != b[i].salary) {
            return 0;
        }
    }
    return 1;
}

static void check(const char *name, struct employee *given, const struct employee *want, size_t n) {
    if (sort_employees(given, n) != 0 || !same(given, want, n)) {
        printf("FAIL %s\n", name);
        failures++;
    } else {
        printf("ok %s\n", name);
    }
}

#define CHECK(name, given, ...)                                         \
    do {                                                                \
        struct employee g[] = given;                                    \
        static const struct employee w[] = __VA_ARGS__;                 \
        _Static_assert(sizeof g == sizeof w, "the same length");        \
        check(name, g, w, sizeof g / sizeof g[0]);                      \
    } while (0)

#define L(...) {__VA_ARGS__}

static const char *const names[40] = {
    "n01", "n02", "n03", "n04", "n05", "n06", "n07", "n08", "n09", "n10",
    "n11", "n12", "n13", "n14", "n15", "n16", "n17", "n18", "n19", "n20",
    "n21", "n22", "n23", "n24", "n25", "n26", "n27", "n28", "n29", "n30",
    "n31", "n32", "n33", "n34", "n35", "n36", "n37", "n38", "n39", "n40",
};

int main(void) {
    CHECK("mixed",
          L({"Ada", "eng", 120}, {"Bob", "sales", 90}, {"Cy", "eng", 150}, {"Di", "ops", 100}),
          {{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Di", "ops", 100}, {"Bob", "sales", 90}});
    CHECK("same-salary-other-dept", L({"Ann", "ops", 100}, {"Ben", "eng", 100}, {"Cat", "hr", 100}),
          {{"Ben", "eng", 100}, {"Cat", "hr", 100}, {"Ann", "ops", 100}});
    if (sort_employees(NULL, 0) != 0) {
        printf("FAIL empty\n");
        failures++;
    } else {
        printf("ok empty\n");
    }
    CHECK("single", L({"Ada", "eng", 120}), {{"Ada", "eng", 120}});
    CHECK("sorted", L({"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}),
          {{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}});
    CHECK("reversed", L({"Bob", "ops", 90}, {"Ada", "eng", 120}, {"Cy", "eng", 150}),
          {{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}});
    CHECK("ties",
          L({"Zoe", "eng", 100}, {"Xi", "hr", 80}, {"Al", "eng", 100}, {"Yu", "hr", 80}, {"Mo", "eng", 100}),
          {{"Zoe", "eng", 100}, {"Al", "eng", 100}, {"Mo", "eng", 100}, {"Xi", "hr", 80}, {"Yu", "hr", 80}});

    // The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
    struct employee given[40], want[40];
    for (size_t i = 0; i < 40; i++) {
        given[i] = (struct employee){names[i], i % 2 ? "a" : "b", 1};
    }
    for (size_t i = 0; i < 20; i++) {
        want[i] = given[2 * i + 1];
        want[20 + i] = given[2 * i];
    }
    check("many-ties", given, want, 40);

    CHECK("case", L({"Ann", "eng", 100}, {"Bea", "Sales", 90}, {"Cal", "ops", 80}),
          {{"Bea", "Sales", 90}, {"Ann", "eng", 100}, {"Cal", "ops", 80}});
    CHECK("non-ascii", L({"Eve", "équipe", 100}, {"Fay", "zoo", 90}, {"Gus", "eng", 80}),
          {{"Gus", "eng", 80}, {"Fay", "zoo", 90}, {"Eve", "équipe", 100}});
    CHECK("negative", L({"Hal", "eng", 0}, {"Ida", "eng", -5}, {"Jo", "eng", 5}),
          {{"Jo", "eng", 5}, {"Hal", "eng", 0}, {"Ida", "eng", -5}});
    CHECK("overflow", L({"Kim", "eng", -2000000000}, {"Lee", "eng", 2000000000}),
          {{"Lee", "eng", 2000000000}, {"Kim", "eng", -2000000000}});
    return failures == 0 ? 0 : 1;
}
SortEmployees.csI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

/// <summary>A record of an employee.</summary>
public sealed record Employee(string Name, string Dept, int Salary);

public static class Employees
{
    /// <summary>
    /// Returns a new list of the records by Dept, then by Salary from high to low.
    /// OrderBy is a stable sort, so records with equal keys keep their input order.
    /// </summary>
    public static List<Employee> SortEmployees(IEnumerable<Employee> employees) =>
        // Give StringComparer.Ordinal: the default comparer of string uses the current culture.
        employees
            .OrderBy(e => e.Dept, StringComparer.Ordinal)
            .ThenByDescending(e => e.Salary)
            .ToList();
}
SortEmployeesTests.cs 58 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

using Xunit;

public sealed class SortEmployeesTests
{
    private static Employee[] E(params (string Name, string Dept, int Salary)[] rows) =>
        rows.Select(r => new Employee(r.Name, r.Dept, r.Salary)).ToArray();

    // The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
    private static readonly Employee[] Many = Enumerable.Range(0, 40)
        .Select(i => new Employee($"n{i + 1:D2}", i % 2 == 1 ? "a" : "b", 1))
        .ToArray();

    public static TheoryData<string, Employee[], Employee[]> Cases => new()
    {
        { "mixed",
          E(("Ada", "eng", 120), ("Bob", "sales", 90), ("Cy", "eng", 150), ("Di", "ops", 100)),
          E(("Cy", "eng", 150), ("Ada", "eng", 120), ("Di", "ops", 100), ("Bob", "sales", 90)) },
        { "same-salary-other-dept",
          E(("Ann", "ops", 100), ("Ben", "eng", 100), ("Cat", "hr", 100)),
          E(("Ben", "eng", 100), ("Cat", "hr", 100), ("Ann", "ops", 100)) },
        { "empty", E(), E() },
        { "single", E(("Ada", "eng", 120)), E(("Ada", "eng", 120)) },
        { "sorted",
          E(("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)),
          E(("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)) },
        { "reversed",
          E(("Bob", "ops", 90), ("Ada", "eng", 120), ("Cy", "eng", 150)),
          E(("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)) },
        { "ties",
          E(("Zoe", "eng", 100), ("Xi", "hr", 80), ("Al", "eng", 100), ("Yu", "hr", 80), ("Mo", "eng", 100)),
          E(("Zoe", "eng", 100), ("Al", "eng", 100), ("Mo", "eng", 100), ("Xi", "hr", 80), ("Yu", "hr", 80)) },
        { "many-ties", Many, [.. Many.Where((_, i) => i % 2 == 1), .. Many.Where((_, i) => i % 2 == 0)] },
        { "case",
          E(("Ann", "eng", 100), ("Bea", "Sales", 90), ("Cal", "ops", 80)),
          E(("Bea", "Sales", 90), ("Ann", "eng", 100), ("Cal", "ops", 80)) },
        { "non-ascii",
          E(("Eve", "équipe", 100), ("Fay", "zoo", 90), ("Gus", "eng", 80)),
          E(("Gus", "eng", 80), ("Fay", "zoo", 90), ("Eve", "équipe", 100)) },
        { "negative",
          E(("Hal", "eng", 0), ("Ida", "eng", -5), ("Jo", "eng", 5)),
          E(("Jo", "eng", 5), ("Hal", "eng", 0), ("Ida", "eng", -5)) },
        { "overflow",
          E(("Kim", "eng", -2000000000), ("Lee", "eng", 2000000000)),
          E(("Lee", "eng", 2000000000), ("Kim", "eng", -2000000000)) },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void SortsByDeptThenSalaryDescending(string name, Employee[] given, Employee[] want)
    {
        Employee[] input = [.. given];
        Assert.True(want.SequenceEqual(Employees.SortEmployees(input)), name);
        Assert.Equal(given, input);
    }
}
sortEmployees.jsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

/** @typedef {{ name: string, dept: string, salary: number }} Employee */

/**
 * Returns a new array of the records by dept, then by salary from high to low.
 * The sort is stable, so records with equal keys keep their input order.
 * @param {readonly Employee[]} employees
 * @returns {Employee[]}
 */
export function sortEmployees(employees) {
  // < compares strings by UTF-16 code units, the same for every locale.
  // The salaries are 32-bit integers, so b.salary - a.salary is exact.
  return employees.toSorted(
    (a, b) => (a.dept < b.dept ? -1 : a.dept > b.dept ? 1 : 0) || b.salary - a.salary,
  );
}

/**
 * Returns a new array of the names in the order of the collation rules of a locale.
 * @param {readonly string[]} names
 * @param {string} locale a BCP 47 language tag, such as "sv"
 * @returns {string[]}
 */
export function sortNames(names, locale) {
  return names.toSorted(new Intl.Collator(locale).compare);
}
sortEmployees.test.js 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { sortEmployees, sortNames } from "./sortEmployees.js";

/** Makes records from [name, dept, salary] rows. */
const rows = (list) =>
  list.map(([name, dept, salary]) => ({ name, dept, salary }));

// The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
const many = Array.from({ length: 40 }, (_, i) => [
  `n${String(i + 1).padStart(2, "0")}`,
  i % 2 ? "a" : "b",
  1,
]);

const cases = {
  mixed: [
    [["Ada", "eng", 120], ["Bob", "sales", 90], ["Cy", "eng", 150], ["Di", "ops", 100]],
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Di", "ops", 100], ["Bob", "sales", 90]],
  ],
  "same-salary-other-dept": [
    [["Ann", "ops", 100], ["Ben", "eng", 100], ["Cat", "hr", 100]],
    [["Ben", "eng", 100], ["Cat", "hr", 100], ["Ann", "ops", 100]],
  ],
  empty: [[], []],
  single: [[["Ada", "eng", 120]], [["Ada", "eng", 120]]],
  sorted: [
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Bob", "ops", 90]],
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Bob", "ops", 90]],
  ],
  reversed: [
    [["Bob", "ops", 90], ["Ada", "eng", 120], ["Cy", "eng", 150]],
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Bob", "ops", 90]],
  ],
  ties: [
    [["Zoe", "eng", 100], ["Xi", "hr", 80], ["Al", "eng", 100], ["Yu", "hr", 80], ["Mo", "eng", 100]],
    [["Zoe", "eng", 100], ["Al", "eng", 100], ["Mo", "eng", 100], ["Xi", "hr", 80], ["Yu", "hr", 80]],
  ],
  "many-ties": [many, [...many.filter((_, i) => i % 2), ...many.filter((_, i) => !(i % 2))]],
  case: [
    [["Ann", "eng", 100], ["Bea", "Sales", 90], ["Cal", "ops", 80]],
    [["Bea", "Sales", 90], ["Ann", "eng", 100], ["Cal", "ops", 80]],
  ],
  "non-ascii": [
    [["Eve", "équipe", 100], ["Fay", "zoo", 90], ["Gus", "eng", 80]],
    [["Gus", "eng", 80], ["Fay", "zoo", 90], ["Eve", "équipe", 100]],
  ],
  negative: [
    [["Hal", "eng", 0], ["Ida", "eng", -5], ["Jo", "eng", 5]],
    [["Jo", "eng", 5], ["Hal", "eng", 0], ["Ida", "eng", -5]],
  ],
  overflow: [
    [["Kim", "eng", -2000000000], ["Lee", "eng", 2000000000]],
    [["Lee", "eng", 2000000000], ["Kim", "eng", -2000000000]],
  ],
};

for (const [name, [given, want]] of Object.entries(cases)) {
  test(name, () => {
    const input = rows(given);
    assert.deepEqual(sortEmployees(input), rows(want));
    assert.deepEqual(input, rows(given), "the input must not change");
  });
}

// The cases of cases/locale.jsonl.
const locales = [
  ["en-accents", "en", ["zebra", "Émile", "apple", "Eve", "eagle"], ["apple", "eagle", "Émile", "Eve", "zebra"]],
  ["en-case", "en", ["b", "B", "a", "A"], ["a", "A", "b", "B"]],
  ["en-accent-order", "en", ["resume", "résumé", "Resume", "rèsume"], ["resume", "Resume", "résumé", "rèsume"]],
  ["sv-letters", "sv", ["ö", "z", "o", "a", "å", "ä"], ["a", "o", "z", "å", "ä", "ö"]],
  ["sv-names", "sv", ["Örjan", "Zara", "Olof", "Åsa", "Anna", "Ärla"], ["Anna", "Olof", "Zara", "Åsa", "Ärla", "Örjan"]],
  ["de-umlaut", "de", ["Äpfel", "Zebra", "Apfel", "apfel"], ["apfel", "Apfel", "Äpfel", "Zebra"]],
  ["da-aa", "da", ["Aase", "Zelda", "Ågot", "Øjvind", "Ærø"], ["Zelda", "Ærø", "Øjvind", "Ågot", "Aase"]],
  ["es-enye", "es", ["llama", "luz", "lzx", "ñu", "nube", "oso"], ["llama", "luz", "lzx", "nube", "ñu", "oso"]],
];

for (const [name, locale, names, want] of locales) {
  test(`locale ${name}`, () => {
    assert.deepEqual(sortNames(names, locale), want);
  });
}
sortEmployees.tsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

export interface Employee {
  readonly name: string;
  readonly dept: string;
  readonly salary: number;
}

/**
 * Returns a new array of the records by dept, then by salary from high to low.
 * The sort is stable, so records with equal keys keep their input order.
 */
export function sortEmployees(employees: readonly Employee[]): Employee[] {
  // < compares strings by UTF-16 code units, the same for every locale.
  // The salaries are 32-bit integers, so b.salary - a.salary is exact.
  return employees.toSorted(
    (a, b) => (a.dept < b.dept ? -1 : a.dept > b.dept ? 1 : 0) || b.salary - a.salary,
  );
}

/** Returns a new array of the names in the order of the collation rules of a locale, such as "sv". */
export function sortNames(names: readonly string[], locale: string): string[] {
  return names.toSorted(new Intl.Collator(locale).compare);
}
sortEmployees.test.ts 86 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { type Employee, sortEmployees, sortNames } from "./sortEmployees.ts";

/** Makes records from [name, dept, salary] rows. */
const rows = (list: readonly (readonly [string, string, number])[]): Employee[] =>
  list.map(([name, dept, salary]) => ({ name, dept, salary }));

// The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
const many: [string, string, number][] = Array.from({ length: 40 }, (_, i) => [
  `n${String(i + 1).padStart(2, "0")}`,
  i % 2 ? "a" : "b",
  1,
]);

const cases: Record<string, [[string, string, number][], [string, string, number][]]> = {
  mixed: [
    [["Ada", "eng", 120], ["Bob", "sales", 90], ["Cy", "eng", 150], ["Di", "ops", 100]],
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Di", "ops", 100], ["Bob", "sales", 90]],
  ],
  "same-salary-other-dept": [
    [["Ann", "ops", 100], ["Ben", "eng", 100], ["Cat", "hr", 100]],
    [["Ben", "eng", 100], ["Cat", "hr", 100], ["Ann", "ops", 100]],
  ],
  empty: [[], []],
  single: [[["Ada", "eng", 120]], [["Ada", "eng", 120]]],
  sorted: [
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Bob", "ops", 90]],
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Bob", "ops", 90]],
  ],
  reversed: [
    [["Bob", "ops", 90], ["Ada", "eng", 120], ["Cy", "eng", 150]],
    [["Cy", "eng", 150], ["Ada", "eng", 120], ["Bob", "ops", 90]],
  ],
  ties: [
    [["Zoe", "eng", 100], ["Xi", "hr", 80], ["Al", "eng", 100], ["Yu", "hr", 80], ["Mo", "eng", 100]],
    [["Zoe", "eng", 100], ["Al", "eng", 100], ["Mo", "eng", 100], ["Xi", "hr", 80], ["Yu", "hr", 80]],
  ],
  "many-ties": [many, [...many.filter((_, i) => i % 2), ...many.filter((_, i) => !(i % 2))]],
  case: [
    [["Ann", "eng", 100], ["Bea", "Sales", 90], ["Cal", "ops", 80]],
    [["Bea", "Sales", 90], ["Ann", "eng", 100], ["Cal", "ops", 80]],
  ],
  "non-ascii": [
    [["Eve", "équipe", 100], ["Fay", "zoo", 90], ["Gus", "eng", 80]],
    [["Gus", "eng", 80], ["Fay", "zoo", 90], ["Eve", "équipe", 100]],
  ],
  negative: [
    [["Hal", "eng", 0], ["Ida", "eng", -5], ["Jo", "eng", 5]],
    [["Jo", "eng", 5], ["Hal", "eng", 0], ["Ida", "eng", -5]],
  ],
  overflow: [
    [["Kim", "eng", -2000000000], ["Lee", "eng", 2000000000]],
    [["Lee", "eng", 2000000000], ["Kim", "eng", -2000000000]],
  ],
};

for (const [name, [given, want]] of Object.entries(cases)) {
  test(name, () => {
    const input = rows(given);
    assert.deepEqual(sortEmployees(input), rows(want));
    assert.deepEqual(input, rows(given), "the input must not change");
  });
}

// The cases of cases/locale.jsonl.
const locales: [string, string, string[], string[]][] = [
  ["en-accents", "en", ["zebra", "Émile", "apple", "Eve", "eagle"], ["apple", "eagle", "Émile", "Eve", "zebra"]],
  ["en-case", "en", ["b", "B", "a", "A"], ["a", "A", "b", "B"]],
  ["en-accent-order", "en", ["resume", "résumé", "Resume", "rèsume"], ["resume", "Resume", "résumé", "rèsume"]],
  ["sv-letters", "sv", ["ö", "z", "o", "a", "å", "ä"], ["a", "o", "z", "å", "ä", "ö"]],
  ["sv-names", "sv", ["Örjan", "Zara", "Olof", "Åsa", "Anna", "Ärla"], ["Anna", "Olof", "Zara", "Åsa", "Ärla", "Örjan"]],
  ["de-umlaut", "de", ["Äpfel", "Zebra", "Apfel", "apfel"], ["apfel", "Apfel", "Äpfel", "Zebra"]],
  ["da-aa", "da", ["Aase", "Zelda", "Ågot", "Øjvind", "Ærø"], ["Zelda", "Ærø", "Øjvind", "Ågot", "Aase"]],
  ["es-enye", "es", ["llama", "luz", "lzx", "ñu", "nube", "oso"], ["llama", "luz", "lzx", "nube", "ñu", "oso"]],
];

for (const [name, locale, names, want] of locales) {
  test(`locale ${name}`, () => {
    assert.deepEqual(sortNames(names, locale), want);
  });
}
sort_employees.goI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

// Package records sorts records of employees.
package records

import (
	"cmp"
	"slices"
	"strings"
)

// Employee is a record of an employee.
type Employee struct {
	Name   string
	Dept   string
	Salary int32
}

// SortEmployees returns a new slice of the records by Dept, then by Salary
// from high to low. Records with equal keys keep their input order.
func SortEmployees(employees []Employee) []Employee {
	sorted := slices.Clone(employees)
	// slices.SortFunc is not stable. SortStableFunc is.
	slices.SortStableFunc(sorted, func(a, b Employee) int {
		// cmp.Or returns the first result that is not 0.
		// strings.Compare compares bytes, so UTF-8 text sorts by code point.
		return cmp.Or(
			strings.Compare(a.Dept, b.Dept),
			cmp.Compare(b.Salary, a.Salary), // b before a: high to low
		)
	})
	return sorted
}
sort_employees_test.go 79 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

package records

import (
	"fmt"
	"slices"
	"testing"
)

type e = Employee

// many returns the 40 records of the many-ties case: depts "b" and "a" in turn,
// all with salary 1. With parity 0 or 1 it returns only the records at even or
// odd positions.
func many(parity int) []Employee {
	var out []Employee
	for i := range 40 {
		if parity >= 0 && i%2 != parity {
			continue
		}
		dept := "b"
		if i%2 == 1 {
			dept = "a"
		}
		out = append(out, e{fmt.Sprintf("n%02d", i+1), dept, 1})
	}
	return out
}

func TestSortEmployees(t *testing.T) {
	cases := []struct {
		name        string
		given, want []Employee
	}{
		{"mixed",
			[]e{{"Ada", "eng", 120}, {"Bob", "sales", 90}, {"Cy", "eng", 150}, {"Di", "ops", 100}},
			[]e{{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Di", "ops", 100}, {"Bob", "sales", 90}}},
		{"same-salary-other-dept",
			[]e{{"Ann", "ops", 100}, {"Ben", "eng", 100}, {"Cat", "hr", 100}},
			[]e{{"Ben", "eng", 100}, {"Cat", "hr", 100}, {"Ann", "ops", 100}}},
		{"empty", []e{}, []e{}},
		{"single", []e{{"Ada", "eng", 120}}, []e{{"Ada", "eng", 120}}},
		{"sorted",
			[]e{{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}},
			[]e{{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}}},
		{"reversed",
			[]e{{"Bob", "ops", 90}, {"Ada", "eng", 120}, {"Cy", "eng", 150}},
			[]e{{"Cy", "eng", 150}, {"Ada", "eng", 120}, {"Bob", "ops", 90}}},
		{"ties",
			[]e{{"Zoe", "eng", 100}, {"Xi", "hr", 80}, {"Al", "eng", 100}, {"Yu", "hr", 80}, {"Mo", "eng", 100}},
			[]e{{"Zoe", "eng", 100}, {"Al", "eng", 100}, {"Mo", "eng", 100}, {"Xi", "hr", 80}, {"Yu", "hr", 80}}},
		{"many-ties", many(-1), append(many(1), many(0)...)},
		{"case",
			[]e{{"Ann", "eng", 100}, {"Bea", "Sales", 90}, {"Cal", "ops", 80}},
			[]e{{"Bea", "Sales", 90}, {"Ann", "eng", 100}, {"Cal", "ops", 80}}},
		{"non-ascii",
			[]e{{"Eve", "équipe", 100}, {"Fay", "zoo", 90}, {"Gus", "eng", 80}},
			[]e{{"Gus", "eng", 80}, {"Fay", "zoo", 90}, {"Eve", "équipe", 100}}},
		{"negative",
			[]e{{"Hal", "eng", 0}, {"Ida", "eng", -5}, {"Jo", "eng", 5}},
			[]e{{"Jo", "eng", 5}, {"Hal", "eng", 0}, {"Ida", "eng", -5}}},
		{"overflow",
			[]e{{"Kim", "eng", -2000000000}, {"Lee", "eng", 2000000000}},
			[]e{{"Lee", "eng", 2000000000}, {"Kim", "eng", -2000000000}}},
	}
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			input := slices.Clone(c.given)
			if got := SortEmployees(input); !slices.Equal(got, c.want) {
				t.Errorf("got %v, want %v", got, c.want)
			}
			if !slices.Equal(input, c.given) {
				t.Errorf("the input changed to %v", input)
			}
		})
	}
}
sort_employees.rsI0tests passRawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

//! Sorts records of employees.

/// A record of an employee.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Employee {
    pub name: String,
    pub dept: String,
    pub salary: i32,
}

/// Sorts the records in place by `dept`, then by `salary` from high to low.
/// The sort is stable, so records with equal keys keep their input order.
pub fn sort_employees(employees: &mut [Employee]) {
    // sort_by is stable. sort_unstable_by is not.
    // str::cmp compares bytes, so UTF-8 text sorts by code point.
    employees.sort_by(|a, b| {
        a.dept.cmp(&b.dept).then_with(|| b.salary.cmp(&a.salary)) // b before a: high to low
    });
}
tests/sort_employees_test.rs 144 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sort-a-list-of-records/.

use algo_sort_a_list_of_records::{Employee, sort_employees};

type Row = (&'static str, &'static str, i32);

fn records(rows: &[Row]) -> Vec<Employee> {
    rows.iter()
        .map(|&(name, dept, salary)| Employee {
            name: name.to_string(),
            dept: dept.to_string(),
            salary,
        })
        .collect()
}

/// The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
fn many() -> Vec<Employee> {
    (0..40)
        .map(|i| Employee {
            name: format!("n{:02}", i + 1),
            dept: if i % 2 == 1 { "a" } else { "b" }.to_string(),
            salary: 1,
        })
        .collect()
}

fn check(name: &str, mut got: Vec<Employee>, want: Vec<Employee>) {
    sort_employees(&mut got);
    assert_eq!(got, want, "case {name}");
}

#[test]
fn cases() {
    let cases: &[(&str, &[Row], &[Row])] = &[
        (
            "mixed",
            &[
                ("Ada", "eng", 120),
                ("Bob", "sales", 90),
                ("Cy", "eng", 150),
                ("Di", "ops", 100),
            ],
            &[
                ("Cy", "eng", 150),
                ("Ada", "eng", 120),
                ("Di", "ops", 100),
                ("Bob", "sales", 90),
            ],
        ),
        (
            "same-salary-other-dept",
            &[("Ann", "ops", 100), ("Ben", "eng", 100), ("Cat", "hr", 100)],
            &[("Ben", "eng", 100), ("Cat", "hr", 100), ("Ann", "ops", 100)],
        ),
        ("empty", &[], &[]),
        ("single", &[("Ada", "eng", 120)], &[("Ada", "eng", 120)]),
        (
            "sorted",
            &[("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)],
            &[("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)],
        ),
        (
            "reversed",
            &[("Bob", "ops", 90), ("Ada", "eng", 120), ("Cy", "eng", 150)],
            &[("Cy", "eng", 150), ("Ada", "eng", 120), ("Bob", "ops", 90)],
        ),
        (
            "ties",
            &[
                ("Zoe", "eng", 100),
                ("Xi", "hr", 80),
                ("Al", "eng", 100),
                ("Yu", "hr", 80),
                ("Mo", "eng", 100),
            ],
            &[
                ("Zoe", "eng", 100),
                ("Al", "eng", 100),
                ("Mo", "eng", 100),
                ("Xi", "hr", 80),
                ("Yu", "hr", 80),
            ],
        ),
        (
            "case",
            &[
                ("Ann", "eng", 100),
                ("Bea", "Sales", 90),
                ("Cal", "ops", 80),
            ],
            &[
                ("Bea", "Sales", 90),
                ("Ann", "eng", 100),
                ("Cal", "ops", 80),
            ],
        ),
        (
            "non-ascii",
            &[
                ("Eve", "équipe", 100),
                ("Fay", "zoo", 90),
                ("Gus", "eng", 80),
            ],
            &[
                ("Gus", "eng", 80),
                ("Fay", "zoo", 90),
                ("Eve", "équipe", 100),
            ],
        ),
        (
            "negative",
            &[("Hal", "eng", 0), ("Ida", "eng", -5), ("Jo", "eng", 5)],
            &[("Jo", "eng", 5), ("Hal", "eng", 0), ("Ida", "eng", -5)],
        ),
        (
            "overflow",
            &[
                ("Kim", "eng", -2_000_000_000),
                ("Lee", "eng", 2_000_000_000),
            ],
            &[
                ("Lee", "eng", 2_000_000_000),
                ("Kim", "eng", -2_000_000_000),
            ],
        ),
    ];
    for &(name, given, want) in cases {
        check(name, records(given), records(want));
    }
}

#[test]
fn many_ties() {
    let given = many();
    let (odd, even): (Vec<_>, Vec<_>) = given
        .iter()
        .cloned()
        .enumerate()
        .partition(|(i, _)| i % 2 == 1);
    let want = odd.into_iter().chain(even).map(|(_, e)| e).collect();
    check("many-ties", given, want);
}
sort_employees.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-a-list-of-records/.

# sort_employees
# Reads records from stdin, one per line: NAME, DEPT and SALARY with a tab between them.
# Prints the records by DEPT, then by SALARY from high to low.
# Records with equal keys keep their input order.
sort_employees() {
  # LC_ALL=C compares bytes, so UTF-8 text sorts by code point, on every machine.
  # -k2,2 is field 2 only. -k3,3nr is field 3 as a number, from high to low.
  # -s turns off the last comparison of whole lines, so equal keys keep their order.
  LC_ALL=C sort -s -t $'\t' -k2,2 -k3,3nr
}
test_sort_employees.bats 43 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sort-a-list-of-records/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/sort_employees.sh"
}

check() { # check GIVEN WANT, with records as "name,dept,salary" and a space between records
  local -a given want
  read -ra given <<<"$1"
  read -ra want <<<"$2"
  run sort_employees <<<"$(printf '%s\n' "${given[@]}" | tr ',' '\t')"
  [ "$status" -eq 0 ]
  [ "$output" = "$(printf '%s\n' "${want[@]}" | tr ',' '\t')" ]
}

@test "mixed" { check "Ada,eng,120 Bob,sales,90 Cy,eng,150 Di,ops,100" "Cy,eng,150 Ada,eng,120 Di,ops,100 Bob,sales,90"; }
@test "same-salary-other-dept" { check "Ann,ops,100 Ben,eng,100 Cat,hr,100" "Ben,eng,100 Cat,hr,100 Ann,ops,100"; }
@test "empty" {
  run sort_employees </dev/null
  [ "$status" -eq 0 ]
  [ -z "$output" ]
}
@test "single" { check "Ada,eng,120" "Ada,eng,120"; }
@test "sorted" { check "Cy,eng,150 Ada,eng,120 Bob,ops,90" "Cy,eng,150 Ada,eng,120 Bob,ops,90"; }
@test "reversed" { check "Bob,ops,90 Ada,eng,120 Cy,eng,150" "Cy,eng,150 Ada,eng,120 Bob,ops,90"; }
@test "ties" { check "Zoe,eng,100 Xi,hr,80 Al,eng,100 Yu,hr,80 Mo,eng,100" "Zoe,eng,100 Al,eng,100 Mo,eng,100 Xi,hr,80 Yu,hr,80"; }
@test "many-ties" {
  # The 40 records of the many-ties case: depts "b" and "a" in turn, all with salary 1.
  local all="" odd="" even="" i rec
  for ((i = 1; i <= 40; i++)); do
    if ((i % 2 == 0)); then rec=$(printf 'n%02d,a,1' "$i"); odd+="$rec "; else rec=$(printf 'n%02d,b,1' "$i"); even+="$rec "; fi
    all+="$rec "
  done
  check "$all" "$odd$even"
}
@test "case" { check "Ann,eng,100 Bea,Sales,90 Cal,ops,80" "Bea,Sales,90 Ann,eng,100 Cal,ops,80"; }
@test "non-ascii" { check "Eve,équipe,100 Fay,zoo,90 Gus,eng,80" "Gus,eng,80 Fay,zoo,90 Eve,équipe,100"; }
@test "negative" { check "Hal,eng,0 Ida,eng,-5 Jo,eng,5" "Jo,eng,5 Hal,eng,0 Ida,eng,-5"; }
@test "overflow" { check "Kim,eng,-2000000000 Lee,eng,2000000000" "Lee,eng,2000000000 Kim,eng,-2000000000"; }

References

  1. The Python HOWTOs, Sorting Techniques, Sort Stability and Complex Sorts; Odds and Ends (the reverse parameter)
  2. The Python Language Reference, Expressions, 6.10.1 Value comparisons (strings, sequences)
  3. Ecma International, ECMA-262, ECMAScript Language Specification, 23.1.3.30 Array.prototype.sort, 23.1.3.30.1 SortIndexedProperties, 23.1.3.30.2 CompareArrayElements, 23.1.3.34 Array.prototype.toSorted
  4. Ecma International, ECMA-262, ECMAScript Language Specification, 7.2.12 IsLessThan (strings compare by code unit)
  5. MDN Web Docs, Intl.Collator, Using locales
  6. Node.js documentation, Internationalization support, Embed the entire ICU (full-icu)
  7. Java SE 25 API, java.util.stream.Stream, sorted(Comparator)
  8. Java SE 25 API, java.util.Comparator, compare, comparingInt, thenComparing(Comparator), reversed
  9. The Java Language Specification, Java SE 25 Edition, 15.18.2 Additive Operators (+ and -) for Numeric Types
  10. Java SE 25 API, java.lang.String, compareTo(String)
  11. Java SE 25 API, java.text.Collator
  12. .NET API reference, Enumerable.OrderBy, Remarks
  13. .NET API reference, List<T>.Sort, Remarks
  14. .NET API reference, StringComparer.Ordinal, Remarks
  15. .NET documentation, Best practices for comparing strings in .NET, String comparisons that use the current culture; String.CompareTo
  16. .NET documentation, Globalization and ICU, Globalization setup in .NET apps, Linux
  17. Go standard library, package slices, SortFunc, SortStableFunc
  18. Go standard library, package cmp, Compare, Or
  19. The Go Programming Language Specification, Comparison operators
  20. The Rust Standard Library, primitive type slice, sort_by, sort_unstable_by
  21. cppreference.com, std::stable_sort
  22. cppreference.com, std::char_traits::eq, std::char_traits::lt
  23. The Open Group, POSIX.1-2024, qsort, Description
  24. The Open Group, POSIX.1-2024, strcmp, Description
  25. The Open Group, POSIX.1-2024, sort, Description; Options (-k, -n, -r, -t); Rationale
  26. GNU Coreutils manual, sort invocation, the last-resort comparison and --stable; -k; footnote 1 (LC_ALL)

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (cpp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (csharp)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (go)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (java)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (javascript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (python)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (rust)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
Code (typescript)I0 not checked yet
  • no problem that the node solves has a contract with shared cases (09.2)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source

The native tests pass in 9 of 10 languages in this build.