-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimple Sorting Algorithm.cpp
50 lines (42 loc) · 1.02 KB
/
Simple Sorting Algorithm.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
#include <iostream>
#include <vector>
using namespace std;
// Function to perform bubble sort
void bubbleSort(vector<int>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; ++i) {
bool swapped = false;
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
swapped = true;
}
}
// Early exit if no swaps were made (array already sorted)
if (!swapped) break;
}
}
// Function to display the array
void displayArray(const vector<int>& arr) {
for (int num : arr) {
cout << num << " ";
}
cout << endl;
}
// nnw
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
vector<int> arr(n);
cout << "Enter " << n << " integers: ";
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
cout << "\nOriginal Array: ";
displayArray(arr);
bubbleSort(arr);
cout << "Sorted Array: ";
displayArray(arr);
return 0;
}