Sorting comparison
Worst-case time and typical auxiliary memory for array implementations. The code inserts each item into its sorted prefix.
| Bubble / insertion | O(n²) time, O(1) space | Can be stable with strict swaps or shifts |
| Selection | O(n²) time, O(1) space | Ordinary selection by swapping is unstable |
| Merge | O(n log n) time, O(n) space | Can be stable |
| Heap | O(n log n) time, O(1) space | Ordinary in-place heap sort is unstable |
| Quick | O(n²) worst, expected O(n log n) with random pivot | Ordinary partition is unstable |
| Counting | O(n + k) time | Needs a bounded key range k |
Python
def insertion_sort(a):
for i in range(1, len(a)):
x, j = a[i], i
while j and a[j-1] > x:
a[j] = a[j-1]
j -= 1
a[j] = xC++
void insertionSort(std::vector<int>& a) {
for (int i = 1; i < (int)a.size(); ++i) {
int x = a[i], j = i;
while (j && a[j-1] > x) { a[j] = a[j-1]; --j; }
a[j] = x;
}
}Java
static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int x = a[i], j = i;
while (j > 0 && a[j-1] > x) { a[j] = a[j-1]; j--; }
a[j] = x;
}
}