Prefer high-level abstractions over low-level handcrafted code
Functions that try to do too much often become hard to read, extend, test, and debug. Functions should be focused and short. An easy way to tell whether or not you should refactor your code into smaller functions is the "And"-test. Describe what your function does. If your descriptions uses and, then you should consider splitting the function into its parts. For your selection sort, you would describe it by:
Iterate over each element. Find the index of the minimum element from the remaining elements and swap if that index is not our current index.
Write the small and focused min_element_index()
and swap()
functions.
#include <vector>
std::size_t min_element_index(const std::vector<int>& vec,
std::size_t startingIndex = 0) {
for (auto candidate = startingIndex + 1; candidate < vec.size();
++candidate) {
if (vec[candidate] < vec[startingIndex]) {
startingIndex = candidate;
}
}
return startingIndex;
}
void swap_by_index(std::vector<int>& vec, int first, int second) {
const auto temp = vec[first];
vec[first] = vec[second];
vec[second] = temp;
}
Let sort()
be a composed function of those two small, focused, and tested functions.
void SelectionSorter::sort(std::vector<int>& vec) {
for (auto currentIndex = 0; currentIndex < vec.size(); ++currentIndex) {
const auto indexOfSmallestItem = min_element_index(vec, currentIndex);
swap_by_index(vec, currentIndex, indexOfSmallestItem);
}
}
We gain reusable functions, avoid magic numbers (-1
), and can const
-qualify our immutable objects.
Prefer to treat warnings as errors
For these small learning programs and new code bases, turn up your warning level and treat warnings as errors. Older code bases should continue to use the same rules that are already being used.
You have mismatched sign comparisons for each std::vector<int>::size()
comparison.
Use the C++ Style Declarator Layout
void SelectionSorter::sort(std::vector<int>& v) {
-------------------------------------------^
Also wasn't sure if the missing space before the {
was intended. Utilize extensions/tools (Clang-Format, Astyle, etc) to maintain the style layout.