Challenge: Count the Swaps
Completed
Print how many swaps bubble sort makes to sort n numbers (this equals the number of pairs in the wrong order).
Input
Line 1: n (n ≤ 2000). Line 2: n whole numbers.
Output
The number of swaps.
Example
Input
5 5 1 4 2 8
Output
4
Editor
C++
Hints
Run bubble sort and count every swap.
Equal neighbours are not swapped.
Solution explanation
Each swap fixes exactly one wrong-order pair. Module 8 counts them faster with merge sort.
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;
long long swaps = 0;
for (int done = 0; done < n - 1; done++)
for (int i = 0; i < n - 1 - done; i++)
if (v[i] > v[i + 1]) { swap(v[i], v[i + 1]); swaps++; }
cout << swaps << endl;
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