Calculating the sum of all numbers
≤ n
#include <cstdint>
// Return the sum of all values from 1 to n.
uint64_t add_to(uint32_t n) {
uint64_t sum = 0;
for (uint32_t i = 1; i <= n; ++i) {
sum += i;
}
return sum;
}
What is wrong with the above naive implementation?
The asymptotic performance is
#include <cstdint>
// Return the sum of all values from 1 to n.
uint64_t add_to(uint32_t n) {
// avoid doubles as they cannot represent numbers close to UINT_MAX correctly
if (n % 2) return ((n + 1ull) / 2) * n;
return (n / 2 * (n + 1ull));
}
Which impact can
clang++ sum_to.cpp -o sum_to
time ./sum_to n
time ./sum_to 1
Despite computers being faster than ever, why are data structures and algorithms still important, even more so than in the past?
Because computers have to deal with larger amounts of data.
Computation time costs energy
How many steps are required, at most, for the following tasks?
Repeatedly step through the list, compare adjacent elements and swaps them
Bubble-sort with Hungarian ("Csángó") folk dance
Exercise: implement the bubble sort algorthm
void bsort(int* array, size_t cnt)
Although simple, it is not used in practice due to
the slow
In practice, don't implement your own search
#include <algorithm> // std::sort
#include <iostream>
#include <vector>
int main () {
std::vector<int> values{ 33, 12, 99, 90, 7, 45 };
std::sort(values.begin(), values.end());
for (const auto& value : values) {
std::cout << value << " ";
}
std::cout << std::endl;
return 0;
}
Download sort.cpp