Sorting
Сортировка
Sorting puts items in a chosen order, such as smallest to largest or newest to oldest. It rearranges the items without adding or removing any.
What it means to sort data
Sorting answers a simple question: what should come before what? For numbers, the rule might be smallest first. For a list of tickets, it might be highest priority first, then earliest creation time. A sort key is the value used to order an item; using more than one key lets you break ties. Sorting is not deduplication: [3, 1, 3] becomes [1, 3, 3], with both copies of 3 intact.
What makes one algorithm different from another?
Insertion sort builds up a sorted section one item at a time. It does little work when items are already close to their final positions, but takes O(n²) time in the worst case. Merge sort splits the input, sorts the pieces, and merges them back together. The standard array implementation takes O(n log n) time and O(n) extra space. Quicksort instead partitions items around a pivot. With random pivot selection its expected running time is O(n log n), but a series of highly uneven partitions can lead to O(n²) time.
An algorithm that learns the order only by comparing items needs Ω(n log n) comparisons in the worst case. That bound does not rule out faster approaches for restricted inputs. Counting sort, for example, counts how many times each integer key occurs. It takes O(n + k) time for n items and a key range of size k, so a very large range can make it a poor choice.
Example: what happens to ties?
scores = [("Maya", 90), ("Jo", 95), ("Sam", 90)]
ranked = sorted(scores, key=lambda row: row[1], reverse=True)
# [('Jo', 95), ('Maya', 90), ('Sam', 90)]
Python's sort is stable: Maya stays ahead of Sam because their scores tie and Maya came first in the input. Stability is different from whether the input is modified. sorted() returns a new list, while scores.sort() sorts the existing list and returns None. Both are stable.
Where sorting helps — and when to skip it
Sorted data makes tables easier to scan, puts equal keys next to each other for grouping, and enables binary search on arrays. In SQL, request the order with ORDER BY rather than relying on the order returned by a previous query. For predictable ordering when several rows share the same timestamp, add a unique tie-breaker, such as an ID. If you only need the largest item, skip sorting altogether: one scan is enough.
What interviewers look for
Before implementing a sort, clarify the order, how ties should behave, and whether you may modify the input. Explain the time and extra space your specific implementation uses. Test it with empty input, duplicates, and data that's already sorted or in reverse order.