forked from Adi8080/Hactoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubbleSort.cpp
59 lines (48 loc) · 1.33 KB
/
BubbleSort.cpp
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 <iostream>
#include <vector>
using namespace std;
void swapping(int &a, int &b) { // Swap the contents of a and b
int temp = a;
a = b;
b = temp;
}
void display(const vector<int>& array) {
for (int value : array) {
cout << value << " ";
}
cout << endl;
}
void bubbleSort(vector<int>& array) {
int n = array.size();
bool swapped;
for (int i = 0; i < n - 1; i++) {
swapped = false;
int lastSwapIndex = n - 1; // Track the last swap index
for (int j = 0; j < lastSwapIndex; j++) {
if (array[j] > array[j + 1]) { // When the current item is bigger than the next
swapping(array[j], array[j + 1]);
swapped = true; // Set swap flag
lastSwapIndex = j; // Update last swap position
}
}
if (!swapped) {
break; // No swap in this pass, so array is sorted
}
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
vector<int> arr(n); // Create a vector with the given number of elements
cout << "Enter elements:" << endl;
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr);
bubbleSort(arr);
cout << "Array after Sorting: ";
display(arr);
return 0;
}