Bubble Sort is an algorithm that sorts an array 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 Insertion 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

Repeat this process until becomes sorted:

  • For , if , swap and .

This algorithm solves the problem in time and space.

void bubble_sort(int n, std::vector<int> &a) {
	while (!std::ranges::is_sorted(a)) {
		for (int i = 1; i < n; i++) {
			if (a[i - 1] > a[i]) {
				std::swap(a[i - 1], a[i]);
			}
		}
	}
}