-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble-sort.cpp
More file actions
59 lines (48 loc) · 1.11 KB
/
bubble-sort.cpp
File metadata and controls
59 lines (48 loc) · 1.11 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
#include<bits/stdc++.h>
using namespace std;
/*
### Non optimized version
class Solution {
public:
vector<int> bubbleSort(vector<int>& nums) {
int n = nums.size();
for (int i=n-1; i>=1; i--) {
for (int j=0; j<=i-1; j++) {
if(nums[j] > nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
return nums;
}
};
*/
class Solution {
public:
vector<int> bubbleSort(vector<int>& nums) {
int n = nums.size();
for (int i=n-1; i>=0; i--) {
bool didSwap = false;
for (int j=0; j<= i-1; j++) {
if (nums[j] > nums[j+1]) {
swap(nums[j], nums[j+1]);
didSwap = true;
}
}
if (!didSwap) {
break;
}
}
return nums;
}
};
int main() {
Solution sol;
vector<int> nums = {3, 2, 1};
sol.bubbleSort(nums);
for (int x : nums) {
cout << x << ", ";
}
}