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. Insert into an appropriate position in .

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++) {
		int x = a[i], j = i;
		for (; j > 0 && a[j - 1] > x; j--) {
			a[j] = a[j - 1];
		}
		a[j] = x;
	}
}

Algorithm 1

Based on Algorithm 0, applying Binary Search to find the appropriate position 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);
	}
}