Insertion Sort is an algorithm that sorts a sequence of numbers in non-decreasing order in time and space.

Tip

This problem can also be solved by Selection Sort in time and space.

Tip

This problem can also be solved by Bubble Sort in time and space.

Tip

This problem can also be solved by Merge Sort in time and space.

Tip

This problem can also be solved by Heapsort in time and space.

Tip

This problem can also be solved by Quicksort in time and space.

Tip

This problem can also be solved by the Manber-Myers Algorithm in time and space.

Algorithm 0

  1. Sort recursively.
  2. Let be the integer in such that , then is the result of sorting .

This algorithm solves the problem in time and space.

void insertion_sort(int n, std::vector<int> &a) {
	for (int i = 1; i < n; i++) {
		for (int j = i; j > 0 && a[j - 1] > a[j]; j--) {
			std::swap(a[j - 1], a[j]);
		}
	}
}

Algorithm 1

Based on Algorithm 0, applying Binary Search to find yields an algorithm that solves the problem in time and space.

void insertion_sort(int n, std::vector<int> &a) {
	for (int i = 1; i < n; i++) {
		std::rotate(std::ranges::lower_bound(a | std::views::take(i), a[i]), a.begin() + i, a.begin() + i + 1);
	}
}