Sorting arranges elements of a collection so that they follow a specified order, such as numeric ascending or lexicographic descending. Formally, given a sequence and a comparator (or a key function), sorting produces a permutation where each element is ordered with respect to the defined rule.
Use built-in sorting with custom keys or comparators when possible; standard libraries are highly optimized and often stable.
# Python: stable, key-based sorting
records = [
{'name': 'Ada', 'age': 34},
{'name': 'Ben', 'age': 34},
{'name': 'Cai', 'age': 29}
]
# Sort by age ascending, then name ascending
out = sorted(records, key=lambda r: (r['age'], r['name']))
print(out)
// JavaScript: comparator-based numeric sort
const nums = [5, 2, 9, 2, 1];
nums.sort((a, b) => a - b); // ascending
console.log(nums); // [1, 2, 2, 5, 9]