forked from waboke/solutions_to_pastquestions_2024
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubblesort.cpp
More file actions
47 lines (39 loc) · 1.11 KB
/
bubblesort.cpp
File metadata and controls
47 lines (39 loc) · 1.11 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
41
42
43
44
45
46
47
#include <iostream>
using namespace std;
// Function to perform bubble sort
void bubbleSort(int* arr, int size) {
for (int i = 0; i < size - 1; ++i) {
for (int j = 0; j < size - i - 1; ++j) {
if (*(arr + j) > *(arr + j + 1)) { // Compare adjacent elements
// Swap elements using pointers
int temp = *(arr + j);
*(arr + j) = *(arr + j + 1);
*(arr + j + 1) = temp;
}
}
}
}
// Function to display the array
void displayArray(int* arr, int size) {
for (int i = 0; i < size; ++i) {
cout << *(arr + i) << " ";
}
cout << endl;
}
int main() {
int n;
cout << "Enter the number of elements in the array: ";
cin >> n;
int* arr = new int[n]; // Dynamically allocate array
cout << "Enter the elements of the array:" << endl;
for (int i = 0; i < n; ++i) {
cin >> *(arr + i);
}
cout << "Original array: ";
displayArray(arr, n);
bubbleSort(arr, n);
cout << "Sorted array: ";
displayArray(arr, n);
delete[] arr; // Free allocated memory
return 0;
}