Sorting is a fundamental algorithm design problem. Many efficient algorithms use sorting as a subroutine, because it is often easier to process data if the elements are in a sorted order.
For example, the question “does an array contain two equal elements?” is easy to answer after sorting: two equal elements are then next to each other. The question “what is the most frequent element?” can be solved in the same way.
For example, the array
| 1 | 3 | 8 | 2 | 9 | 2 | 5 | 6 |
becomes after sorting:
| 1 | 2 | 2 | 3 | 5 | 6 | 8 | 9 |
O(n2) algorithms
Simple sorting algorithms work in O(n2) time. They are short and usually consist of two nested loops. A famous one is bubble sort, where the elements “bubble” in the array according to their values.
Bubble sort consists of n rounds. On each round, the algorithm goes through the array, and whenever two consecutive elements are in the wrong order, it swaps them:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
for (int i = 0; i < n; i++) cout << a[i] << " ";
cout << "\n";
}
8 1 3 8 2 9 2 5 6
Output
1 2 2 3 5 6 8 9
After the first round the largest element is in its correct position, and in general, after k rounds the k largest elements are in their correct positions. So after n rounds the whole array is sorted. The first round swaps the elements of the array above as follows:
| 1 | 3 | 2 | 8 | 9 | 2 | 5 | 6 |
| 1 | 3 | 2 | 8 | 2 | 9 | 5 | 6 |
| 1 | 3 | 2 | 8 | 2 | 5 | 9 | 6 |
| 1 | 3 | 2 | 8 | 2 | 5 | 6 | 9 |
The same round, printed by a program after every swap:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
// only the first round, printing the array after every swap
for (int j = 0; j < n - 1; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
for (int x : a) cout << x << " ";
cout << "\n";
}
}
}
8 1 3 8 2 9 2 5 6
Output
1 3 2 8 9 2 5 6 1 3 2 8 2 9 5 6 1 3 2 8 2 5 9 6 1 3 2 8 2 5 6 9
Run the algorithm step by step in the diagram: the input values are the size of the array and its elements, one per line.
Inversions
Bubble sort always swaps consecutive elements. Such an algorithm always needs at least O(n2) time in the worst case, because O(n2) swaps may be needed.
A useful concept when analyzing sorting algorithms is an inversion: a pair of elements (a[i], a[j]) with i < j and a[i] > a[j], that is, two elements in the wrong order. For example, the array
| 1 | 2 | 2 | 6 | 3 | 5 | 9 | 8 |
has three inversions: (6,3), (6,5) and (9,8). The program counts them by checking all pairs:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
long long inv = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
cout << "(" << a[i] << "," << a[j] << ") ";
inv++;
}
}
}
cout << "\n" << inv << "\n";
}
8 1 2 2 6 3 5 9 8
Output
(6,3) (6,5) (9,8) 3
The number of inversions tells how much work is needed to sort the array. A sorted array has no inversions, and an array in reverse order has the largest possible number: 1 + 2 + … + (n − 1) = n(n − 1)/2 = O(n2).
Swapping two consecutive elements that are in the wrong order removes exactly one inversion. So if an algorithm only swaps consecutive elements, each swap removes at most one inversion, and the algorithm needs at least O(n2) time.
O(n log n) algorithms
An array can be sorted in O(n log n) time by algorithms that are not limited to swapping consecutive elements. One of them is merge sort (invented by J. von Neumann in 1945), which is based on recursion. It sorts a subarray a[lo..hi] as follows:
- If lo = hi, do nothing: the subarray is already sorted.
- Find the middle position k = ⌊(lo + hi)/2⌋.
- Recursively sort
a[lo..k]. - Recursively sort
a[k+1..hi]. - Merge the sorted subarrays
a[lo..k]anda[k+1..hi]into the sorted subarraya[lo..hi].
Merge sort is efficient because it halves the size of the subarray at each step. The recursion has O(log n) levels and each level takes O(n) time: merging is linear because both halves are already sorted. For example, the array
| 1 | 3 | 6 | 2 | 8 | 2 | 5 | 9 |
is divided into two halves, which are sorted recursively:
| 1 | 2 | 3 | 6 | 2 | 5 | 8 | 9 |
and finally the halves are merged into the sorted array:
| 1 | 2 | 2 | 3 | 5 | 6 | 8 | 9 |
#include <bits/stdc++.h>
using namespace std;
vector<int> a, b;
// sorts a[lo..hi]
void mergeSort(int lo, int hi) {
if (lo >= hi) return;
int k = (lo + hi) / 2;
mergeSort(lo, k);
mergeSort(k + 1, hi);
// merge a[lo..k] and a[k+1..hi]
int i = lo, j = k + 1;
for (int p = lo; p <= hi; p++) {
if (j > hi || (i <= k && a[i] <= a[j])) b[p] = a[i++];
else b[p] = a[j++];
}
for (int p = lo; p <= hi; p++) a[p] = b[p];
}
int main() {
int n;
cin >> n;
a.resize(n);
b.resize(n);
for (int i = 0; i < n; i++) cin >> a[i];
mergeSort(0, n - 1);
for (int i = 0; i < n; i++) cout << a[i] << " ";
cout << "\n";
}
8 1 3 6 2 8 2 5 9
Output
1 2 2 3 5 6 8 9
Sorting lower bound
Can an array be sorted faster than in O(n log n) time? Not when the algorithm is based on comparing elements. Think of sorting as a process where every comparison “x < y?” gives more information about the array: the comparisons form a binary tree, and its leaves are all possible orders of the array, n! of them. The height of the tree is therefore at least
log2(n!) = log2(1) + log2(2) + … + log2(n) ≥ (n/2) · log2(n/2),
(we keep only the last n/2 terms and replace each by log2(n/2)). So in the worst case every comparison sort needs at least about n log n steps.
Counting sort
The lower bound does not apply to algorithms that do not compare elements but use other information. Counting sort sorts an array in O(n) time, assuming that every element is an integer between 0 and c, where c = O(n).
The algorithm makes a bookkeeping array whose indices are the values of the original array, and counts how many times each value appears. The array
| 1 | 3 | 6 | 9 | 9 | 3 | 5 | 9 |
corresponds to the following bookkeeping array (the indices 1–9 are above the boxes):
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
| 1 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 3 |
For example, position 3 holds 2, because the value 3 appears twice. Making the bookkeeping array takes O(n) time, and then the sorted array is written out in O(n) time as well. Counting sort can only be used when c is small enough for the values to be indices. In the program the first input line is n and c:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, c;
cin >> n >> c; // n elements, each between 0 and c
vector<int> a(n), cnt(c + 1, 0);
for (int i = 0; i < n; i++) {
cin >> a[i];
cnt[a[i]]++; // bookkeeping array
}
for (int v = 1; v <= c; v++) cout << cnt[v] << " ";
cout << "\n";
// the sorted array: each value v cnt[v] times
for (int v = 0; v <= c; v++) {
for (int k = 0; k < cnt[v]; k++) cout << v << " ";
}
cout << "\n";
}
8 9 1 3 6 9 9 3 5 9
Output
1 0 2 0 1 1 0 0 3 1 3 3 5 6 9 9 9
Based on: Antti Laaksonen, Competitive Programmer's Handbook, section 3.1 (CC BY-NC-SA 4.0). Changed: the text is shortened and adapted, the code fragments are complete programs, and the diagrams, tasks and quizzes are new. Adaptation: Boban Blagojević, CC BY-NC-SA 4.0.