Skip to content

Commit 10c379a

Browse files
authored
Merge pull request #231 from Kryptonite-18/Kryptonite-18-patch-1
Create bubble.cpp
2 parents 4aeed17 + eee410c commit 10c379a

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

bubble.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Optimized implementation of Bubble sort
2+
#include <bits/stdc++.h>
3+
using namespace std;
4+
5+
// An optimized version of Bubble Sort
6+
void bubbleSort(int arr[], int n)
7+
{
8+
int i, j;
9+
bool swapped;
10+
for (i = 0; i < n - 1; i++) {
11+
swapped = false;
12+
for (j = 0; j < n - i - 1; j++) {
13+
if (arr[j] > arr[j + 1]) {
14+
swap(arr[j], arr[j + 1]);
15+
swapped = true;
16+
}
17+
}
18+
19+
// If no two elements were swapped
20+
// by inner loop, then break
21+
if (swapped == false)
22+
break;
23+
}
24+
}
25+
26+
// Function to print an array
27+
void printArray(int arr[], int size)
28+
{
29+
int i;
30+
for (i = 0; i < size; i++)
31+
cout << " " << arr[i];
32+
}
33+
34+
// Driver program to test above functions
35+
int main()
36+
{
37+
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
38+
int N = sizeof(arr) / sizeof(arr[0]);
39+
bubbleSort(arr, N);
40+
cout << "Sorted array: \n";
41+
printArray(arr, N);
42+
return 0;
43+
}
44+
// This code is contributed by shivanisinghss2110

0 commit comments

Comments
 (0)