-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_sort.cpp
40 lines (32 loc) · 951 Bytes
/
selection_sort.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
#include <iostream>
#include <vector>
int count = 0;
std::vector<int>& selection_sort(std::vector<int>& vec) {
for (int i = 0; i < vec.size(); ++i) {
int indexMin = i;
for (int j = i+1; j < vec.size(); ++j) {
if (vec[j] < vec[indexMin]) {
indexMin = j;
}
count++;
}
int tmp = vec[i];
vec[i] = vec[indexMin];
vec[indexMin] = tmp;
}
return vec;
}
std::ostream& operator<<(std::ostream& out, std::vector<int> const& vec) {
out << "[ ";
for (int i = 0; i < vec.size(); ++i) {
out << vec[i] << " ";
}
out << "]";
return out;
}
int main() {
std::vector<int> vec = {0, 3, 2, 5, 6, 8, 1, 9, 4, 2, 1, 2, 9, 6, 4, 1, 7, -1, -5, 23, 6, 2, 35, 6, 3, 32};
std::cout << vec << '\n'; // [ 0 3 2 5 6 8 1 9 4 2 1 2 9 6 4 1 7 -1 -5 23 6 2 35 6 3 32 ]
std::cout << selection_sort(vec) << '\n'; // [-5 - 1 0 1 1 1 2 2 2 2 3 3 4 4 5 6 6 6 6 7 8 9 9 23 32 35]
std::cout << count; //325
}