ArticlesCost

Cost

Linearithmic time

n times log n. The usual cost of a good sort, and the cost you can sometimes beat when the input is already ordered.

O(n log n) is the cost of doing a logarithmic amount of work for every element, or of doing linear work at each of about log n levels. Merge sort is the picture: each level merges n elements, and there are about log n levels. The product is linearithmic.

Good general-purpose sorts live here. If you sort and then scan, say O(n log n) out loud and ask whether the sort was required. Sorted squares can be produced in linear time because the input is already ordered. Sorting the squares afterwards works, and it is slower than the shape of the data allows.

When a heap does less ordering than a full sort, or a hash map avoids ordering entirely, you are often leaving O(n log n) for something flatter. Name that trade. Do not treat a sort as free just because it is one function call.