-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection_sort.cpp
More file actions
50 lines (33 loc) · 913 Bytes
/
Copy pathselection_sort.cpp
File metadata and controls
50 lines (33 loc) · 913 Bytes
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
#include <iostream>
#include <vector>
using namespace std;
int findSmallestIndex(const vector<int>& arr) {
int smallest = arr[0];
int smallestIndex = 0;
for(int i = 1; i < arr.size(); i++) {
if (arr[i] < smallest) {
smallest = arr[i];
smallestIndex = i;
}
}
return smallestIndex;
}
vector<int> selectionSort(vector<int> arr) {
vector<int> newArr;
newArr.reserve(arr.size());
while (!arr.empty()) {
int smallest = findSmallestIndex(arr);
int smallestElement = arr[smallest];
arr.erase(arr.begin() + smallest);
newArr.push_back(smallestElement);
}
return newArr;
}
int main() {
vector<int> v{12, 2, 65, 100, 11, 5, 9};
vector<int> sorted = selectionSort(v);
for (int i = 0; i < sorted.size(); i++) {
cout << sorted[i] << " ";
}
return 0;
}