Skip to content

Commit 8717790

Browse files
created bubble sort
1 parent 4a65335 commit 8717790

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

bubble sort

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// C++ program for implementation of Bubble sort
2+
#include
3+
using namespace std;
4+
5+
int main() {
6+
int arr[] = {4, 1, 5, 3, 2};
7+
// Finding the size of the array
8+
auto n = end(arr) - begin(arr);
9+
// Sorting array_A in ascending order
10+
for(int it = 0; it < (n - 1); it++){
11+
int flag = 0;
12+
for(int i = 0; i < (n - 1); i++){
13+
// Comparing adjacent elements
14+
if(arr[i] > arr[i + 1]){
15+
// Since the element at i is greater,
16+
//swap elements at index i and i+1
17+
int temp = arr[i];
18+
arr[i] = arr[i + 1];
19+
arr[i + 1] = temp;
20+
flag = 1;
21+
}
22+
}
23+
// Optimization. Break the outer for loop
24+
// if no element is swapped in the inner for loop.
25+
if(flag == 0){
26+
break;
27+
}
28+
}
29+
// Printing the sorted array
30+
for(int i = 0; i < n; i++){
31+
cout<< arr[i] << " ";
32+
}
33+
return 0;
34+
}

0 commit comments

Comments
 (0)