Sorting Algorithms

Sorting as a tool: std::sort, comparators, sorting structs.

Sorting is the most used algorithm in contests — not as a goal in itself, but as a tool: after sorting, a problem often simplifies radically. The closest pair of numbers? Sort — and it will be among the neighbors. A greedy choice? It almost always begins with "sort by...". You don't need to write sorting by hand: std::sort runs in O(n log n). What you need is to control it — to supply a comparator, i.e. the comparison rule.

Sorting in ascending and descending order. Enter: 5, then 3 1 4 1 5

A comparator is a function "should x come before y". The lambda [](int x, int y) { return x > y; } gives descending order. The real power is sorting structs by any field. Let's sort students by score: the comparison rule reads straight out of the code.

Enter: 3, then lines of the form "name score": Azat 90, Aigul 98, Bek 85

Python

The same in Python: the key parameter. Same input

Good to know: std::stable_sort preserves the order of equal elements (important when sorting "by score, ties by name" in two passes). Task: sort a list of words first by length, and for equal lengths — alphabetically (hint: a comparator with two conditions). Mark the lesson as completed and move on to the two pointers technique.
Доска