LearnFrenzy
Sign in Take a free test

STL Algorithms and Ranges · Lesson 25 of 33

Sorting with the STL

5 min read Updated Nov 7, 2026 Saurabh Samir

Sorting is the first step of countless solutions: binary search, two pointers, greedy algorithms, removing duplicates. std::sort sorts a million numbers in a few milliseconds, and its relatives handle stable ordering, "top K" and "k-th smallest" efficiently. Writing a correct comparator is the key skill.

In this lesson

  • std::sort ascending, descending and with comparators
  • Sorting structs by several keys
  • stable_sort
  • partial_sort and nth_element

std::sort

#include <algorithm>
#include <functional>
#include <iostream>
#include <string>
#include <vector>

template <typename C> void show(const C& c) { for (const auto& x : c) std::cout << x << ' '; std::cout << '\n'; }

int main() {
    std::vector<int> v{42, 7, 93, 18, 7, 55};
    std::sort(v.begin(), v.end());                           // ascending
    show(v);
    std::sort(v.begin(), v.end(), std::greater<int>());      // descending
    show(v);
    std::sort(v.begin(), v.end(), [](int a, int b) {         // even numbers first, each group ascending
        if (a % 2 != b % 2) return a % 2 == 0;
        return a < b;
    });
    show(v);

    std::string word = "algorithm";
    std::sort(word.begin(), word.end());                     // strings are sortable ranges too
    std::cout << word << '\n';
    return 0;
}

Output

7 7 18 42 55 93 
93 55 42 18 7 7 
18 42 7 7 55 93 
aghilmort

std::sort is an introsort (quicksort + heapsort + insertion sort): O(n log n) guaranteed. It needs random-access iterators (vector, array, deque, string).

Sorting structs

#include <algorithm>
#include <iostream>
#include <string>
#include <tuple>
#include <vector>

struct Product { std::string name; double price; int rating; };

int main() {
    std::vector<Product> items{{"Mouse", 599, 4}, {"Keyboard", 2499, 5}, {"Hub", 1299, 4},
                               {"Stand", 1499, 5}, {"Pad", 299, 3}};
    // rating high→low, then price low→high
    std::sort(items.begin(), items.end(), [](const Product& a, const Product& b) {
        return std::tie(b.rating, a.price) < std::tie(a.rating, b.price);
    });
    for (const auto& p : items) std::cout << p.rating << "* " << p.name << " " << p.price << '\n';
    return 0;
}

Output

5* Stand 1499
5* Keyboard 2499
4* Mouse 599
4* Hub 1299
3* Pad 299

Comparator rules

  • Return true only if a must come strictly before b. a <= b breaks std::sort (it can read out of bounds or loop).
  • Be consistent: if a < b and b < c then a < c.
  • Take parameters by const& – copying strings or structs on every comparison is slow.

stable_sort

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

struct Order { int id; std::string city; };

int main() {
    std::vector<Order> orders{{101, "Pune"}, {102, "Delhi"}, {103, "Pune"}, {104, "Agra"}, {105, "Delhi"}};
    std::stable_sort(orders.begin(), orders.end(),
                     [](const Order& a, const Order& b) { return a.city < b.city; });
    for (const auto& o : orders) std::cout << o.city << ' ' << o.id << " | ";
    std::cout << '\n';
    return 0;
}

Output

Agra 104 | Delhi 102 | Delhi 105 | Pune 101 | Pune 103 | 

A stable sort keeps equal elements in their original order – within each city, order ids stay ascending. std::sort doesn't promise this. Stability lets you sort by several keys in passes: sort by the secondary key first, then stable-sort by the primary key.

partial_sort and nth_element

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores{45, 92, 13, 78, 88, 61, 99, 70, 54};

    std::vector<int> a = scores;
    std::partial_sort(a.begin(), a.begin() + 3, a.end(), std::greater<int>());   // only the top 3 sorted
    std::cout << "top 3: " << a[0] << ' ' << a[1] << ' ' << a[2] << '\n';

    std::vector<int> b = scores;
    std::nth_element(b.begin(), b.begin() + b.size() / 2, b.end());    // median in O(n) on average
    std::cout << "median: " << b[b.size() / 2] << '\n';

    std::vector<int> c = scores;
    std::nth_element(c.begin(), c.begin() + 1, c.end());               // 2nd smallest
    std::cout << "2nd smallest: " << c[1] << '\n';
    return 0;
}

Output

top 3: 99 92 88
median: 70
2nd smallest: 45
AlgorithmResultComplexity
sorteverything in orderO(n log n)
stable_sortin order, equal elements keep their orderO(n log n)
partial_sort(first, mid, last)the smallest (mid − first) sorted at the frontO(n log k)
nth_element(first, nth, last)the element at nth is the one that would be there if sorted; smaller ones before, larger afterO(n) average
is_sortedchecks orderO(n)

Practice

Try it yourself

  1. Sort strings so that shorter ones come first and, for equal length, in reverse alphabetical order.

    Show solution
    #include <algorithm>
    #include <iostream>
    #include <string>
    #include <vector>
    
    int main() {
        std::vector<std::string> w{"set", "map", "deque", "array", "list"};
        std::sort(w.begin(), w.end(), [](const std::string& a, const std::string& b) {
            return a.size() != b.size() ? a.size() < b.size() : a > b;
        });
        for (const auto& s : w) std::cout << s << ' ';
        std::cout << '\n';
        return 0;
    }

    Output

    set map list deque array 

Quick check

Is std::sort stable?

No – use std::stable_sort when equal elements must keep their order.

Which algorithm finds the median in O(n) on average?

std::nth_element.

Why is return a <= b; a broken comparator?

It returns true for equal elements, violating strict weak ordering.

Summary

  • std::sort is O(n log n); pass std::greater or a lambda for custom orders.
  • Comparators must be strict; std::tie makes multi-key comparisons short.
  • stable_sort keeps ties in order; partial_sort and nth_element do less work when you need less.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links