{ }codelper

Learn › Python

Going further · 17

Sorting

Put values in order: smallest first, largest first, or by a rule you choose.

Sorting puts values in order.
The example below sorts numbers smallest first and largest first, then sorts words alphabetically and "shortest first".

nums = list(map(int, input().split()))words = input().split()print(*sorted(nums))print(*sorted(nums, reverse=True))print(*sorted(words))print(*sorted(words, key=lambda w: (len(w), w)))
stdin
10 9 1 25 3
pear fig banana kiwi apple
stdout
1 3 9 10 25
25 10 9 3 1
apple banana fig kiwi pear
fig kiwi pear apple banana

Key points

  • By default, numbers go by size and strings by dictionary order (character-code order).
  • Some sorts return a new list and some change the list in place.
    Python sorted(nums) returns a new list; nums.sort() works in place.
  • There are two ways to give a rule.
    A key function says what to compare for each value (Python key=lambda w: (len(w), w) means "by length, then alphabetically").
  • A compare function takes two values and returns a negative number if the first goes first, 0 if they tie, and a positive number if the second goes first.
  • A stable sort keeps tied values in their original order.
    With a sort that is not stable, write the tie-break (same length → alphabetical) into the compare function too.

How each language writes it

Pythonsorted(nums) (new list), nums.sort() (in place).
Largest first with reverse=True, a rule with key=lambda w: (len(w), w).
Stable
JavaScriptarr.sort((a, b) => a - b) — in place.
Without a compare function even numbers are compared as strings.
Chain rules with a.length - b.length || ....
Stable since ES2019
TypeScriptSame as JavaScript
JavaArrays.sort, Collections.sort.
Largest first with Comparator.reverseOrder(), a rule with Comparator.comparingInt(String::length).thenComparing(...).
Object arrays and Collections.sort are stable.
int[] takes no comparator
C#Array.Sort and List.Sort (in place, not guaranteed stable), LINQ OrderBy(...).ThenBy(...) and OrderByDescending (stable)
C++std::sort(v.begin(), v.end()), largest first with std::greater<int>().
A compare lambda returns a bool: "does the first go first?".
Use std::stable_sort when you need stability
Cqsort(a, n, sizeof a[0], cmp) — cmp takes two pointers and returns negative, 0 or positive.
Not guaranteed stable
Craykonlist.Sort() sorts smallest first.
Pass a compare function's name, as in list.Sort(ShortestFirst).
Stable

Common mistakes

Writing nums = nums.sort()Python

nums = [3, 1, 2]
nums = nums.sort()
print(nums)

→ None — sort works in place and returns nothing

Write just nums.sort(), or nums = sorted(nums).

Sorting numbers with plain sort()JavaScript · TypeScript

console.log([10, 9, 1].sort());

→ [ 1, 10, 9 ] — the numbers are compared as strings

Always pass (a, b) => a - b for numbers.

Passing a comparator for an int[]Java

int[] a = {3, 1, 2};
Arrays.sort(a, Comparator.reverseOrder());

→ Compile error — the int[] version of sort takes no comparator

Convert to Integer[] as the example does, or sort smallest first and read backwards.

How languages differ
Writing a C qsort comparator as return a - b; overflows int when you subtract a large positive from a large negative (e.g.
-2000000000 - 2000000000), flipping the sign and the order.
Compare instead: (a > b) - (a < b).

Practice