Workspace Sorting
0d
DSA Cheat Sheets

Sorting comparison

Worst-case time and typical auxiliary memory for array implementations. The code inserts each item into its sorted prefix.

Bubble / insertionO(n²) time, O(1) spaceCan be stable with strict swaps or shifts
SelectionO(n²) time, O(1) spaceOrdinary selection by swapping is unstable
MergeO(n log n) time, O(n) spaceCan be stable
HeapO(n log n) time, O(1) spaceOrdinary in-place heap sort is unstable
QuickO(n²) worst, expected O(n log n) with random pivotOrdinary partition is unstable
CountingO(n + k) timeNeeds 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] = x

C++

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;
  }
}