-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.cpp
More file actions
40 lines (37 loc) · 1.01 KB
/
BubbleSort.cpp
File metadata and controls
40 lines (37 loc) · 1.01 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
#include <iostream>
using namespace std;
void BubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
bool swapped = false; // Optimization: Track if any swaps were made in this pass
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true; // Set swapped to true if a swap occurred
}
}
if (!swapped) {
// If no swaps were made in this pass, the array is already sorted
break;
}
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i];
if (i < size - 1) {
cout << " ";
}
}
cout << endl;
}
int main() {
int arr[] = {8, 4, 11, 32, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Unsorted Array" << endl;
printArray(arr, n);
cout << endl;
BubbleSort(arr, n);
cout << "Sorted array" << endl;
printArray(arr, n);
return 0;
}