Sorting arranges values in a useful order. Many problems become easier after sorting because relationships become predictable.
For example, after sorting an array, two pointers can move inward to solve pair-sum problems efficiently.
Common sorting algorithms
Bubble sort
Bubble sort repeatedly swaps adjacent values that are out of order. It is easy to understand but slow for large inputs.
Time complexity: O(n²).
Selection sort
Selection sort repeatedly finds the smallest remaining value and moves it into position.
Time complexity: O(n²).
Merge sort
Merge sort splits the array, sorts both halves, then merges them.
Time complexity: O(n log n).
Quick sort
Quick sort picks a pivot and partitions values around it.
Average time complexity: O(n log n).
JavaScript sorting warning
JavaScript’s default .sort() converts values to strings unless you provide a comparator.
[10, 2, 5].sort(); // [10, 2, 5] as string order
[10, 2, 5].sort((a, b) => a - b); // [2, 5, 10]
When sorting helps
- finding pairs
- removing duplicates
- grouping close values
- scheduling intervals
- greedy algorithms
Practice problems
- Sort numbers ascending.
- Merge two sorted arrays.
- Remove duplicates from a sorted array.
- Find the minimum number of meeting rooms.
- Sort intervals and merge overlaps.
Practice links
Interactive walkthrough