I'm trying to write selection sort. Everything works but my algorithm is not looping through whole vector _item
leaving my v_sorted
too short. Elements are sorted properly.
sort.hpp
template<typename T>
std::vector<T> selection_sort(std::vector<T>);
sort.cpp
template<typename T>
std::vector<T> selection_sort(std::vector<T> _item) {
std::vector<T> v_sorted;
for(int i = 0; i < _item.size(); ++i) {
T smallest = _item[0];
for(auto const& j : _item) {
if(j < smallest) {
smallest = j;
}
}
v_sorted.push_back(smallest);
auto it = std::find(_item.begin(), _item.end(), smallest);
if (it != _item.end()) {
// to prevent moving all of items in vector
// https://stackoverflow.com/a/15998752
std::swap(*it, _item.back());
_item.pop_back();
}
}
return v_sorted;
}
template std::vector<int> selection_sort(std::vector<int> _item);
sort_tests.hpp
BOOST_AUTO_TEST_CASE(selection_sort_int)
{
std::vector<int> v_unsorted = {3, 1, 2, 7, 6};
std::vector<int> v_sorted = {1, 2, 3, 6, 7};
auto v_test = exl::selection_sort(v_unsorted);
BOOST_CHECK_EQUAL_COLLECTIONS(v_sorted.begin(), v_sorted.end(),
v_test.begin(), v_test.end());
}
This test is failing with Collections size mismatch: 5 != 3
. Any test is failing with size mismatch. Loop is stopping (in this case) after three iterations. Thanks in advance for any clues.