1
Sorting Algorithms Comparison
★★★★★
↑ Index
Algorithm › Sort
| Algorithm | Best | Average | Worst | Space | Stable |
|---|
| Bubble Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Selection Sort | O(n²) | O(n²) | O(n²) | O(1) | No |
| Insertion Sort | O(n) | O(n²) | O(n²) | O(1) | Yes |
| Merge Sort | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick Sort | O(n log n) | O(n log n) | O(n²) | O(log n) | No |
| Heap Sort | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting Sort | O(n + k) | O(n + k) | O(n + k) | O(k) | Yes |
Stable = equal elements keep their original order. In-place = O(1) extra memory. C++ sort() uses Introsort (quick + heap + insertion), O(n log n).
2
Merge Sort
★★★★★
↑ Index
Algorithm › Sort
Divide and conquer: split the array into halves, sort each half recursively, then merge the two sorted halves. Always O(n log n), stable, needs O(n) extra space.

Split down to single elements, then merge back in order
C++
void merge(vector<int> &a, int l, int m, int r) {
vector<int> tmp;
int i = l, j = m + 1;
while (i <= m && j <= r)
tmp.push_back(a[i] <= a[j] ? a[i++] : a[j++]);
while (i <= m) tmp.push_back(a[i++]);
while (j <= r) tmp.push_back(a[j++]);
for (int k = 0; k < tmp.size(); k++) a[l + k] = tmp[k];
}
void mergeSort(vector<int> &a, int l, int r) {
if (l >= r) return;
int m = l + (r - l) / 2;
mergeSort(a, l, m);
mergeSort(a, m + 1, r);
merge(a, l, m, r);
}
Recurrence: T(n) = 2T(n/2) + O(n) → O(n log n).
3
Quick Sort
★★★★★
↑ Index
Algorithm › Sort
Pick a pivot, partition the array so smaller elements are on the left and larger on the right, then sort both sides recursively. Average O(n log n), in-place. Worst case O(n²) when the pivot is always the smallest/largest (e.g. already sorted input with last-element pivot); a random pivot avoids it.

After one partition the pivot is at its final index
C++
int partition(vector<int> &a, int low, int high) { // Lomuto
int pivot = a[high];
int i = low - 1;
for (int j = low; j < high; j++)
if (a[j] < pivot) swap(a[++i], a[j]);
swap(a[i + 1], a[high]);
return i + 1;
}
void quickSort(vector<int> &a, int low, int high) {
if (low < high) {
int p = partition(a, low, high);
quickSort(a, low, p - 1);
quickSort(a, p + 1, high);
}
}
Q & A
- Merge sort vs quick sort?
Merge sort: always O(n log n), stable, needs O(n) extra memory, good for linked lists and external sorting. Quick sort: in-place and usually faster in practice, but O(n²) in the worst case and not stable.