实现选择排序与向量向量

2023-09-11 06:44:07 作者:壞蛋先森.

我试图实现一个功能,使用排序选择排序是随机生成的载体。我想一个天真的方式只是为了看看,如果我能得到它的正常工作。这里是我的尝试:

I am attempting to implement a function that sorts a randomly generated vector using selection sort. I am trying a naive way just to see if I can get it working correctly. Here is my attempt:

void selection_sort(std::vector<int>& v)
{
    int pos, min, i;
    //std::vector<int>::iterator pos, min, i;

    for( pos = v[0]; pos < v[30]; ++pos)
    {
        min = pos;

        for( i = v[pos + 1]; i < v[30]; ++i)
        {   
            if( i < min)
            {
                min = i;
            }
        }

        if( min != pos)
        {   
            std::swap(v.at(min), v.at(pos));

        }
    }
}

出于某种原因,但是当我再次显示向量,所有的元素都在以相同的顺序,因为他们原本。我不知道,如果我不使用的std ::交换正确,或者如果我选择排序是不正确写入。我相信答案是很轻松,但我无法看到它。感谢您的帮助提前。

For some reason however when I display the vector again, all of the elements are in the exact same order as they were originally. I am not sure if I am not using std::swap correctly or if my selection sort is not written correctly. I am sure the answer is trivially easy, but I can not see it. Thanks for your help in advance.

推荐答案

您的问题是,你要立足各地实际值的循环的载体,没有载体的指标。

Your problem is that you're trying to base your loops around the actual values in the vector, not the indexes in the vector.

因此​​,如果您的载体是随机生成的,你说这样的:

So if your vector is randomly generated, and you say this:

for( pos = v[0]; pos < v[30]; ++pos)

有一个机会,以v的值[0]大于V [30]。这样的循环将永远不会运行。我看到了同样的问题,在这个循环:

There is a chance that the value at v[0] is greater than v[30]. Thus the loop would never run. I see the same problem in this loop:

for( i = v[pos + 1]; i < v[30]; ++i)

所以,我建议你使用索引为实际的循环。尝试是这样的:

So I'd recommend using indexes for the actual looping. Try something like:

for( pos = 0; pos < 30; ++pos)
{
  min = v[pos];

等等...

etc...

编辑:正如下面提到的,它也将是更好的基于你的矢量大小的循环。然而,为了节省你的自我,从每次循环运行时调用昂贵的size()方法,只要抓住大小循环开始之前。例如:

As mentioned below, it would also be better to base your loop of the size of the of the vector. However, to save your self from calling the expensive size() method every time the loops runs, just grab the size before the loop starts. For example:

size_t size = v.size();
for(size_t pos = 0; pos < size; ++pos)