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
32namespace algorithms {
33
34// ─── Sorting ─────────────────────────────────────────────────────────────────
35
55template <typename T>
56void 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
87template <typename T>
88void 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
119inline 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
147inline 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
170inline 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
189template <typename T>
190T 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
bool is_prime(unsigned n)
Test whether a number is prime.
std::uint64_t fibonacci(unsigned n)
Compute the -th Fibonacci number.
T sum(const std::vector< T > &data)
Compute the sum of all elements in a range.
void insertion_sort(std::vector< T > &data)
Sort a vector in-place using insertion sort.
void bubble_sort(std::vector< T > &data)
Sort a vector in-place using bubble sort.
unsigned gcd(unsigned a, unsigned b)
Compute the greatest common divisor of two integers.