Challenge: Bubble Sort, Pass by Pass
Completed
Bubble sort n numbers and print the vector after every pass. Stop as soon as a pass makes no swaps (still print that pass).
Input
Line 1: n (n ≥ 2). Line 2: n whole numbers.
Output
One line per pass.
Example
Input
5 5 1 4 2 8
Output
1 4 2 5 8 1 2 4 5 8 1 2 4 5 8
Editor
C++
Hints
Outer loop = passes, inner loop = compare neighbours.
Print after each pass, then stop if nothing swapped.
Solution explanation
The swapped flag makes an already-sorted vector take a single pass.
Show solution
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
for (int done = 0; done < n - 1; done++) {
bool swapped = false;
for (int i = 0; i < n - 1 - done; i++)
if (v[i] > v[i + 1]) { swap(v[i], v[i + 1]); swapped = true; }
for (int i = 0; i < n; i++) cout << v[i] << (i + 1 < n ? " " : "\n");
if (!swapped) break;
}
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module