-
Notifications
You must be signed in to change notification settings - Fork 0
/
14bubble_sort.cpp
81 lines (68 loc) · 2.01 KB
/
14bubble_sort.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// 14. Implement Bubble sort algorithm to sort elements of
// an array in ascending and descending order.
// Theory:
// This code demonstrates two sorting functions: ascendingsort and
// descendingsort. Both functions implement the bubble sort algorithm
// to sort an array of integers in ascending and descending order,
// respectively. Bubble sort repeatedly steps through the list,
// compares adjacent elements, and swaps them if they are in the wrong
// order. This process is repeated until the array is sorted.
#include <iostream>
using namespace std;
void ascendingsort(int arr[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < n - i - 1; ++j)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void descendingsort(int arr[], int n)
{
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < n - i - 1; ++j)
{
if (arr[j] < arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main()
{
int n;
cout << "enter number of elements in array: ";
cin >> n;
int arr[n];
cout << "enter elements of array: ";
for (int i = 0; i < n; ++i)
cin >> arr[i];
ascendingsort(arr, n);
cout << "array in ascending order: ";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
descendingsort(arr, n);
cout << "array in descending order: ";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
return 0;
}
// Conclusion:
// The bubble sort algorithm presented in the code provides a simple
// approach to sorting elements in an array. However, it has a time
// complexity of O(n^2), making it inefficient for large datasets
// compared to more efficient sorting algorithms like merge sort or
// quicksort.