-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubblesort.cpp
More file actions
76 lines (57 loc) · 1.63 KB
/
bubblesort.cpp
File metadata and controls
76 lines (57 loc) · 1.63 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
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
/*
Bubblesort:
Worst case: n^2 -> It runs n^2 comparisons, if the array is sorted before n^2 iterations it will stop
Best case: n -> When the vector is already sorted the n_swaps variable will stop the algorithm
average case: n^2 ->
stable: -> Yes
Description:
It runs n^2 times on the vector, checking whether the element i and i+1 fulfils the evaluator,
if otherwise, it swaps them.
**** Similar to selectionsort and insertionsort, but with worst constant factor ****
*/
#ifndef BUBBLESORT
#define BUBBLESORT
#define SWAP(a,b, swap_tmp) ({swap_tmp=a; a=b; b=swap_tmp;})
template <typename T, typename Func>
void bubblesort(T *v, int size, Func eval) {
int n_swaps;
T swap_tmp;
// it iterates n times
for (int i=0; i<size; i++) {
n_swaps = 0;
// for each i iteration, it through the size - i, since each i iteration it takes a extreme value to the end
for (int j=1; j<size-i; j++)
if (eval(v[j], v[j-1])) {
SWAP(v[j-1], v[j], swap_tmp);
n_swaps++;
}
// When the vector is sorted, then no swap would have been made, this stops the algorithm
if (n_swaps==0) break;
}
}
// Default order set on ascending
template <typename T>
void bubblesort(T *v, int size) {
bubblesort(v, size, [] (T a, T b) {return a<b;});
}
#ifndef VECTOR_TEST
// Testing
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "vector_utility.cpp"
using namespace std;
int main() {
srand(time(0));
int size=100;
int v[size];
initRandomV(v, size, (int)size, (int)0.0);
printV(v, size);
bubblesort(v, size, [] (int a, int b){ return a>b; });
printV(v, size);
bubblesort(v, size);
printV(v, size);
return 0;
}
#endif
#endif