Functions | |
| template<typename T> | |
| void | bubble_sort (std::vector< T > &data) |
| Sort a vector in-place using bubble sort. | |
| std::uint64_t | fibonacci (unsigned n) |
| Compute the \(n\)-th Fibonacci number. | |
| unsigned | gcd (unsigned a, unsigned b) |
| Compute the greatest common divisor of two integers. | |
| template<typename T> | |
| void | insertion_sort (std::vector< T > &data) |
| Sort a vector in-place using insertion sort. | |
| bool | is_prime (unsigned n) |
| Test whether a number is prime. | |
| template<typename T> | |
| T | sum (const std::vector< T > &data) |
| Compute the sum of all elements in a range. | |
| void algorithms::bubble_sort | ( | std::vector< T > & | data | ) |
Sort a vector in-place using bubble sort.
Repeatedly steps through the list, swaps adjacent elements that are out of order, and repeats until no swaps are needed.
Complexity:
\[ \text{Time: } O(n^2), \qquad \text{Space: } O(1) \]
| T | Element type (must support operator<). |
| data | The vector to sort. |
std::sort in production.Definition at line 56 of file algorithms.hpp.
|
inline |
Compute the \(n\)-th Fibonacci number.
Uses the recurrence:
\[ F(n) = F(n-1) + F(n-2), \quad F(0) = 0, \; F(1) = 1 \]
Implemented iteratively for \(O(n)\) time and \(O(1)\) space.
| n | The index (0-based). |
n > 93 when using uint64_t. Definition at line 119 of file algorithms.hpp.
|
inline |
Compute the greatest common divisor of two integers.
Uses the Euclidean algorithm:
\[ \gcd(a, 0) = a, \qquad \gcd(a, b) = \gcd(b, \; a \bmod b) \]
| a | First integer. |
| b | Second integer. |
a and b.std::gcd from <numeric> (C++17) instead. Definition at line 147 of file algorithms.hpp.
| void algorithms::insertion_sort | ( | std::vector< T > & | data | ) |
Sort a vector in-place using insertion sort.
Builds the sorted portion one element at a time by inserting each new element into its correct position.
Complexity:
\[ \text{Best: } O(n), \quad \text{Average/Worst: } O(n^2), \quad \text{Space: } O(1) \]
| T | Element type (must support operator<). |
| data | The vector to sort. |
std::sort ( \(O(n \log n)\)). Definition at line 88 of file algorithms.hpp.
|
inline |
Test whether a number is prime.
Uses trial division up to \(\sqrt{n}\):
\[ \text{Time: } O(\sqrt{n}) \]
| n | The number to test. |
true if n is prime, false otherwise.is_prime(0) == false, is_prime(1) == false, is_prime(2) == true, is_prime(97) == true. Definition at line 170 of file algorithms.hpp.
| T algorithms::sum | ( | const std::vector< T > & | data | ) |
Compute the sum of all elements in a range.
| T | Numeric type. |
| data | The input vector. |
Definition at line 190 of file algorithms.hpp.