C++ · Module 14 · Lesson 21 min read

Sorting & Custom Comparators

std::sort (<algorithm>)

CSS
std::sort(v.begin(), v.end());                 // ascending using <
std::sort(v.begin(), v.end(), std::greater{}); // descending
std::sort(v.begin(), v.end(), [](const E& a, const E& b) { return a.amount < b.amount; });

O(n log n). Needs random-access iterators. Not stable: equal elements may change order.

Comparator rules ⚠️ (strict weak ordering)

  • Return true only if a should come strictly before b
  • Never <=: comp(a, a) must be false — violating this is undefined behaviour (can crash!)
  • Consistent: if a < b and b < c then a < c

Multi-key sorting

CSS
[](const E& a, const E& b) {
    if (a.category != b.category) return a.category < b.category;
    return a.amount > b.amount;            // then amount descending
}

or with std::tie(a.category, b.amount) < std::tie(b.category, a.amount).

Other sorting algorithms

AlgorithmUse
std::stable_sortkeep equal elements in original order (e.g. sort by date, then stable-sort by category)
std::partial_sort(b, b + k, e)only the first k sorted (top-k)
std::nth_element(b, b + k, e)k-th element in place, O(n) average — medians
std::is_sortedcheck
std::reversereverse a range

Ranges version (C++20)

c
std::ranges::sort(v);
std::ranges::sort(people, {}, &Person::age);   // sort by a member: a "projection" ✅

Sorting other containers

  • std::list → l.sort(comp)
  • std::map/std::set are always sorted by key; to sort a map by value, copy into a vector of pairs

Example

C++
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

struct Expense {
    std::string date, category;
    double amount;
};

void print(const std::vector<Expense>& v, const char* title) {
    std::cout << title << ":\n";
    for (const auto& e : v) std::cout << "  " << e.date << "  " << e.category << "  " << e.amount << '\n';
}

int main() {
    std::vector<Expense> list = {
        { "11-03", "Food", 450 }, { "11-01", "Rent", 15000 }, { "11-02", "Food", 1200 },
        { "11-01", "Travel", 300 }, { "11-03", "Travel", 800 }, { "11-02", "Bills", 2300 } };

    std::sort(list.begin(), list.end(), [](const Expense& a, const Expense& b) {
        if (a.category != b.category) return a.category < b.category;   // category A-Z
        return a.amount > b.amount;                                      // then amount high-low
    });
    print(list, "by category, then amount");

    std::ranges::sort(list, {}, &Expense::date);                          // projection: sort by date
    std::stable_sort(list.begin(), list.end(),
                     [](const Expense& a, const Expense& b) { return a.category < b.category; });
    print(list, "stable by category (dates stay in order within each category)");

    std::vector<int> amounts = { 450, 15000, 1200, 300, 800, 2300, 99 };
    std::partial_sort(amounts.begin(), amounts.begin() + 3, amounts.end(), std::greater{});
    std::cout << "top 3: " << amounts[0] << ' ' << amounts[1] << ' ' << amounts[2] << '\n';

    std::vector<int> m = { 9, 1, 8, 2, 7, 3, 5 };
    std::nth_element(m.begin(), m.begin() + m.size() / 2, m.end());
    std::cout << "median: " << m[m.size() / 2] << '\n';

    std::vector<int> d = { 5, 2, 9 };
    std::sort(d.begin(), d.end(), std::greater{});
    std::cout << "descending: " << d[0] << ' ' << d[1] << ' ' << d[2]
              << ", is_sorted ascending? " << std::boolalpha << std::is_sorted(d.begin(), d.end()) << '\n';
    return 0;
}

/* Output:
by category, then amount:
  11-02  Bills  2300
  11-02  Food  1200
  11-03  Food  450
  11-01  Rent  15000
  11-03  Travel  800
  11-01  Travel  300
stable by category (dates stay in order within each category):
  11-02  Bills  2300
  11-02  Food  1200
  11-03  Food  450
  11-01  Rent  15000
  11-01  Travel  300
  11-03  Travel  800
top 3: 15000 2300 1200
median: 5
descending: 9 5 2, is_sorted ascending? false
*/