doxyYoda 0.2.2
A modern Doxygen theme — CSS Grid, fog-over-fen, dark mode
☾
Toggle main menu visibility
Loading...
Searching...
No Matches
algorithms.hpp
Go to the documentation of this file.
1
11
12
#pragma once
13
14
#include <algorithm>
15
#include <cstdint>
16
#include <numeric>
17
#include <vector>
18
31
32
namespace
algorithms
{
33
34
// ─── Sorting ─────────────────────────────────────────────────────────────────
35
55
template
<
typename
T>
56
void
bubble_sort
(std::vector<T>& data) {
57
bool
swapped;
58
for
(std::size_t i = 0; i < data.size(); ++i) {
59
swapped =
false
;
60
for
(std::size_t j = 0; j + 1 < data.size() - i; ++j) {
61
if
(data[j + 1] < data[j]) {
62
std::swap(data[j], data[j + 1]);
63
swapped =
true
;
64
}
65
}
66
if
(!swapped)
break
;
67
}
68
}
69
87
template
<
typename
T>
88
void
insertion_sort
(std::vector<T>& data) {
89
for
(std::size_t i = 1; i < data.size(); ++i) {
90
T key = data[i];
91
std::size_t j = i;
92
while
(j > 0 && key < data[j - 1]) {
93
data[j] = data[j - 1];
94
--j;
95
}
96
data[j] = key;
97
}
98
}
99
100
// ─── Numeric ─────────────────────────────────────────────────────────────────
101
119
inline
std::uint64_t
fibonacci
(
unsigned
n) {
120
if
(n <= 1)
return
n;
121
std::uint64_t a = 0, b = 1;
122
for
(
unsigned
i = 2; i <= n; ++i) {
123
std::uint64_t c = a + b;
124
a = b;
125
b = c;
126
}
127
return
b;
128
}
129
147
inline
unsigned
gcd
(
unsigned
a,
unsigned
b) {
148
while
(b != 0) {
149
unsigned
t = b;
150
b = a % b;
151
a = t;
152
}
153
return
a;
154
}
155
170
inline
bool
is_prime
(
unsigned
n) {
171
if
(n < 2)
return
false
;
172
if
(n < 4)
return
true
;
173
if
(n % 2 == 0 || n % 3 == 0)
return
false
;
174
for
(
unsigned
i = 5; i * i <= n; i += 6) {
175
if
(n % i == 0 || n % (i + 2) == 0)
return
false
;
176
}
177
return
true
;
178
}
179
189
template
<
typename
T>
190
T
sum
(
const
std::vector<T>& data) {
191
return
std::accumulate(data.begin(), data.end(), T{});
192
}
193
194
}
// namespace algorithms
195
// end of algorithms group
algorithms
Definition
algorithms.hpp:32
algorithms::is_prime
bool is_prime(unsigned n)
Test whether a number is prime.
Definition
algorithms.hpp:170
algorithms::fibonacci
std::uint64_t fibonacci(unsigned n)
Compute the -th Fibonacci number.
Definition
algorithms.hpp:119
algorithms::sum
T sum(const std::vector< T > &data)
Compute the sum of all elements in a range.
Definition
algorithms.hpp:190
algorithms::insertion_sort
void insertion_sort(std::vector< T > &data)
Sort a vector in-place using insertion sort.
Definition
algorithms.hpp:88
algorithms::bubble_sort
void bubble_sort(std::vector< T > &data)
Sort a vector in-place using bubble sort.
Definition
algorithms.hpp:56
algorithms::gcd
unsigned gcd(unsigned a, unsigned b)
Compute the greatest common divisor of two integers.
Definition
algorithms.hpp:147
demo
src
algorithms.hpp
Generated by
1.17.0
Generated by
Doxygen 1.17.0
Analytics by
Antics
provided by
TurtleTech ehf