Sorting
Bubble Sort
Repeatedly walk the array comparing adjacent pairs and swapping any that are
out of order. After pass k, the k largest elements are in their final
positions at the end. Stop early when a full pass makes zero swaps.
Algorithm
Canonical input [5, 1, 4, 2, 8] finishes after three passes: two with
swaps, then a clean pass that triggers the early exit. Final array
[1, 2, 4, 5, 8].
Basic Implementation
basic.cpp
#include <iostream>
#include <vector>
int main() {
std::vector<int> arr = {5, 1, 4, 2, 8};
int n = static_cast<int>(arr.size());
for (int i = 0; i < n - 1; ++i) {
bool swapped = false;
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
std::cout << "[";
for (size_t i = 0; i < arr.size(); ++i) {
if (i > 0) std::cout << ", ";
std::cout << arr[i];
}
std::cout << "]" << std::endl;
return 0;
}
Complexity
- Time: O(n^2) worst and average; O(n) best (already sorted with early exit)
- Space: O(1)
- Stable: yes
Implementation notes
- In C++, the input is a
std::vector<int>initialized as{5, 1, 4, 2, 8}andnis copied fromstatic_cast<int>(arr.size())for the loop bounds. - The outer loop uses
int iand stops ati < n - 1; the inner loop usesint jand stops atj < n - i - 1, so eacharr[j + 1]read is inside the vector. - Swaps are manual:
int tmp = arr[j], then two assignments into adjacent vector slots. The checked source does not callstd::swap. bool swappedis reset each pass and set only after a vector mutation. The trace shows pass 1 moving through[1, 4, 2, 5, 8], pass 2 reaching[1, 2, 4, 5, 8], and pass 3 breaking withswapped == false.- Output is streamed with
std::cout, asize_tprint loop, comma separators, andstd::endl, producing[1, 2, 4, 5, 8]. - Visible allocation is the vector storage from the initializer list; mutation
is limited to vector element assignments, the scalar
tmp, andswapped.
adjacent-pair compare and swap
Inner loop walks `j` from `0` to `n - i - 2` comparing `arr[j]` and `arr[j + 1]`.
early exit
A `swapped` flag set false at the start of each pass. If no swap happened, break out of the outer loop.