-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_swap.cpp
51 lines (38 loc) · 980 Bytes
/
count_swap.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
int countSwapsToSort(std::vector<int>& arr) {
int n = arr.size();
int numSwaps = 0;
bool swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
swapped = true;
numSwaps++;
}
}
if (!swapped) {
// N?u không có s? hoán d?i trong vòng l?p trong, m?ng dã du?c s?p x?p
break;
}
}
return numSwaps;
}
int main() {
std::vector<int> arr;
std::string input;
std::getline(std::cin, input);
std::istringstream iss(input);
int num;
while (iss >> num) {
arr.push_back(num);
}
int numSwaps = countSwapsToSort(arr);
// In ra s? l?n d?o (swap)
std::cout << numSwaps << std::endl;
return 0;
}