-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbubble_sort.h
More file actions
39 lines (35 loc) · 788 Bytes
/
bubble_sort.h
File metadata and controls
39 lines (35 loc) · 788 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
#ifndef BUBBLE_SORT_HEADER
#define BUBBLE_SORT_HEADER
#include "../helper/utils.h"
/**
* Bubble Sort
* Average complexity: O(n^2)
* Best Case: O(n^2)
* Worst Case: O(n^2)
* Space: O(1)
*/
void bubble_sort(int a[], int n) {
for (int j = n; j > 1; --j)
for (int i = 1; i < j; ++i)
if (a[i - 1] > a[i])
swap(a[i - 1], a[i]);
}
/**
* Bubble Sort Optimize
* Average complexity: O(n^2)
* Best Case: O(n)
* Worst Case: O(n^2)
* Space: O(1)
* Stable
*/
void bubble_sort_optimize1(int a[], int n) {
for (int j = n; j > 1; --j) {
bool stop = true;
for (int i = 1; i < j; ++i)
if (a[i - 1] > a[i])
swap(a[i - 1], a[i]),
stop = false;
if (stop) break;
}
}
#endif