What makes a good sort

5 things you ask of it · Part of Search and sort

Key idea

Practice

6 questions · about 3 min

Explained step by step

Sorting algorithm

A sorting algorithm puts data in an order: numbers from smallest to largest, words alphabetically, or by whatever rule is needed. To compare algorithms, 5 things are looked at: speed; whether it sorts in place, without an extra array; whether it's stable, that is whether it respects the order among equal elements; whether it's adaptive, that is whether it takes advantage of what's already sorted; and whether it sorts by comparing elements or not.

An adaptive sort takes advantage of the order the data already has: if it comes almost sorted, it works much less. Its best case is usually quite a bit better than its average case. Insertion sort and bubble sort with early exit are adaptive: with already sorted data they're O(n). Selection sort isn't: it always does O(n²).

A comparison sort decides the order by comparing pairs of elements with less than, equal or greater than. Almost every well-known one is. They have a limit: in the worst case they can't go below O(n log n). Those that don't compare, like counting sort or radix sort, can reach O(n), but only work for certain data, like integers in a small range.

Sorting is used a lot because sorted data is easier to search, analyze and process. In a sorted list you search with binary search, find duplicates because they end up together, compute the median by looking at the middle one and merge 2 lists in a single pass. Often, sorting first turns a slow problem into a fast one.

Since no algorithm does it all, you choose by case. For little data or almost sorted data, insertion sort. For lots of data in general, quick sort, which is fast and in place. If stability is needed, merge sort. If the data is integers in a small range, counting sort or radix sort. Languages combine several: for example, quick sort for the big parts and insertion sort for the small pieces.

Stable sort

A sort is stable if 2 equal elements stay in the same relative order they had before. It matters when sorting by several criteria. If you have students sorted by name and sort them by age with a stable algorithm, those with the same age stay sorted by name. With an unstable one, that order can be lost.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

5 things you ask of it