-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbubble_sort.cpp
More file actions
35 lines (28 loc) · 743 Bytes
/
bubble_sort.cpp
File metadata and controls
35 lines (28 loc) · 743 Bytes
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
#include <iostream>
using namespace std;
// Function to perform Bubble Sort
void bubbleSort(int arr[], int n) {
for(int i = 0; i < n - 1; i++) {
for(int j = 0; j < n - i - 1; j++) {
// Swap if elements are in wrong order
if(arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int n;
cout << "Enter number of elements: ";
cin >> n;
int* arr = new int[n]; // dynamic array
cout << "Enter elements:\n";
for(int i = 0; i < n; i++)
cin >> arr[i];
bubbleSort(arr, n);
cout << "Sorted array: ";
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
delete[] arr; // free memory
return 0;
}