-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsortstrategy.cpp
More file actions
78 lines (59 loc) · 1.79 KB
/
Copy pathsortstrategy.cpp
File metadata and controls
78 lines (59 loc) · 1.79 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include </Users/user/source/sortstrategy.h>
sortstrategy::~sortstrategy(){
}
void sortstrategy :: Print(const std::vector<int>& vector)const{
for(int i : vector){
std::cout<<i<<" ";
}
}
void bubblesortstrategy :: sort(std::vector<int>& vector){
bool swap = true;
while(swap){
swap = false;
for (size_t i = 0; i < vector.size()-1; i++) {
if (vector[i]>vector[i+1] ){
vector[i] += vector[i+1];
vector[i+1] = vector[i] - vector[i+1];
vector[i] -=vector[i+1];
swap = true;
}
}
}
}
void selectionsortstrategy :: sort(std::vector<int>& vector){
for (int currentIndex = 0; currentIndex < vector.size() - 1; currentIndex++) {
int minIndex = currentIndex;
for (int i = currentIndex + 1; i < vector.size(); i++) {
if (vector[i] < vector[minIndex]) {
minIndex = i;
}
}
if (minIndex != currentIndex) {
int temp = vector[currentIndex];
vector[currentIndex] = vector[minIndex];
vector[minIndex] = temp;
}
}
}
void quicksortstrategy :: sort(std::vector<int>& vector){
if (vector.size() <= 1) {
return; // Already sorted
}
int pivot = vector[vector.size() / 2];
std::vector<int> left;
std::vector<int> right;
for (int element : vector) {
if (element < pivot) {
left.push_back(element);
} else if (element > pivot) {
right.push_back(element);
}
}
sort(left);
sort(right);
vector.clear();
vector.insert(vector.end(), left.begin(), left.end());
vector.push_back(pivot);
vector.insert(vector.end(), right.begin(), right.end());
}