-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.cpp
More file actions
52 lines (41 loc) · 990 Bytes
/
BubbleSort.cpp
File metadata and controls
52 lines (41 loc) · 990 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
// BUBBLE SORT (Adaptive (with swapped) & Stable)
// Time Average & Worst: O(n^2) Time Best: O(n) || Space: O(1)
void bubbleSort(int arr[], int arrSize)
{
for (int i = 0; i < arrSize - 1; ++i)
{
bool swapped = false;
for (int j = 0; j < arrSize - i - 1; ++j)
{
if (arr[j] > arr[j + 1])
{
std::swap(arr[j], arr[j + 1]);
swapped = true;
}
}
if (!swapped)
break;
}
}
void printArr(int arr[], int arrSize)
{
std::cout << "{ ";
for (int i = 0; i < arrSize; ++i)
{
std::cout << arr[i] << " ";
}
std::cout << "}" << std::endl;
}
int main()
{
// Bubble Sort
int A[] = {50, 70, 60, 40, 80, 10, 20, 30};
int aSize = sizeof(A) / sizeof(A[0]);
std::cout << "A: ";
printArr(A, aSize);
bubbleSort(A, aSize);
std::cout << "A after Bubble Sort: ";
printArr(A, aSize);
return 0;
}