【问题标题】:Selection sort - loop stops too early选择排序 - 循环过早停止
【发布时间】:2017-10-19 11:05:37
【问题描述】:

我正在尝试编写选择排序。一切正常,但我的算法没有循环整个向量 _item 让我的 v_sorted 太短。元素排序正确。

排序.hpp

template<typename T>
std::vector<T> selection_sort(std::vector<T>);

排序.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());
}

此测试因Collections size mismatch: 5 != 3 而失败。任何测试都因大小不匹配而失败。循环在三次迭代后停止(在这种情况下)。提前感谢您提供任何线索。

【问题讨论】:

  • 考虑pop_back()的效果。
  • 如果您不确定,请在循环开头添加std::cout &lt;&lt; "i = " &lt;&lt; i &lt;&lt; ", _item.size() = " &lt;&lt; _item.size() &lt;&lt; std::endl;

标签: c++ sorting


【解决方案1】:

for 循环的++i_item.pop_back() 的同时作用具有增加两次的效果,而您只想增加一次。

将for循环改为while循环:

while(!_item.empty()) 

Live Demo

【讨论】:

  • 就是这样!非常感谢!
【解决方案2】:

你正在重新实现std::min_element,如果你使用它,你不需要再次找到元素,你也不想改变_item的大小,同时循环它的@987654324 @。

也可以就地排序,如下:

template<typename T>
std::vector<T> selection_sort(std::vector<T> _item) {
    for(auto it = _item.begin(); it != _item.end(); ++it) {
        auto smallest = std::min_element(it, _item.end());
        std::iter_swap(it, smallest);
    }
    return _item;
}

【讨论】:

  • @SirGuy 哎呀,好消息。我现在大约到达this example
猜你喜欢
  • 2018-06-09
  • 2013-10-08
  • 1970-01-01
  • 2018-09-19
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多