Counting Sort is an algorithm that sorts an array of integers 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 Insertion 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 Quickselect in time and space.

Algorithm

  1. For each in , find the number of occurrences of in .
  2. is the result of sorting .

This algorithm solves the problem in time and space.

void counting_sort(int n, int m, std::vector<int> &a) {
	std::vector cnt(m, 0);
	for (int i = 0; i < n; i++) {
		cnt[a[i]]++;
	}
	for (int i = 0, j = 0; i < m; i++) {
		while (cnt[i]--) {
			a[j++] = i;
		}
	}
}