Skip to content

Commit 6e476d5

Browse files
Create Bubble Sort.cpp
1 parent 4ec2944 commit 6e476d5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Basics/Bubble Sort.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
int32_t main() {
5+
ios_base::sync_with_stdio(0);
6+
cin.tie(0);
7+
int n; cin >> n;
8+
int a[n + 1];
9+
for (int i = 1; i <= n; i++) {
10+
cin >> a[i];
11+
}
12+
int swaps = 0;
13+
for (int step = 1; step <= n - 1; step++) {
14+
for (int i = 1; i < n; i++) {
15+
if (a[i] > a[i + 1]) {
16+
swap(a[i], a[i + 1]);
17+
++swaps;
18+
}
19+
}
20+
}
21+
cout << "Array is sorted in " << swaps << " swaps.\n";
22+
cout << "First Element: " << a[1] << '\n';
23+
cout << "Last Element: " << a[n] << '\n';
24+
return 0;
25+
}
26+
// https://vjudge.net/problem/HackerRank-ctci-bubble-sort

0 commit comments

Comments
 (0)