-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble.cpp
More file actions
45 lines (39 loc) · 883 Bytes
/
Copy pathbubble.cpp
File metadata and controls
45 lines (39 loc) · 883 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
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;
void printVector(vector<int> &vec) {
int size = vec.size();
for (int i = 0; i < size; i++) {
cout << vec[i] << ", ";
}
cout << endl;
}
// need the & before vec to include the actual vector instead of a copy of hte
// vector
void bubbleSort(vector<int> &vec) {
int size = vec.size();
while (true) {
int swap = 0;
for (int i = 0; i < size - 1; i++) {
if (vec[i] > vec[i + 1]) {
int firstVal = vec[i];
int nextVal = vec[i + 1];
vec[i] = nextVal;
vec[i + 1] = firstVal;
swap++;
}
}
if (swap == 0) {
break;
}
}
}
int main() {
vector<int> data = {5, 1, 4, 2, 8};
cout << "Beginning Vector: ";
printVector(data);
bubbleSort(data);
cout << "Sorted Vector in Ascending Order: ";
printVector(data);
}