简体   繁体   English

实现链接列表的选择排序

[英]Implementing Selection Sort for Linked Lists

I am trying to implement a selection sort algorithm that will work with linked lists and will use iterators to scrool through them. 我正在尝试实现一个选择排序算法,该算法将与链表一起使用,并将使用迭代器来通过它们。 The selection sort algorithm is the following: for each element of the list except the last one(let's call it K ), it will seek out the smallest on from the position we are currently on(so it will start from K until the last element). 选择排序算法如下:对于列表中除最后一个元素之外的每个元素(让我们称之为K ),它将从我们当前所处的位置中寻找最小的元素(因此它将从K开始直到最后一个元素)。 After that it will swap K and the smallest element. 之后,它将swap K and the smallest element.

I think that my mistake is in the first for loop; 我认为我的错误是在第一个for循环中; I am very unsure that --a.end() is the pre-last element. 我不确定--a.end()是前一个元素。 I get some output, though it is wrong. 我得到一些输出,虽然这是错误的。

#include <iostream>
#include <list>

using namespace std;

void sort_list(list<int>& a)
{
    //from the first until the pre-last element
    for(list<int> :: iterator itr = a.begin(); itr != (--a.end()); ++itr)
    {
            int smallest = *itr;

        //get smallest element after current index
         list<int> :: iterator itr2 =itr;
          ++itr2;
    for(; itr2 != a.end(); ++itr2)
        {
                if (smallest > *itr2)
                   {
                       smallest = *itr2;
                   } 
        }
        //swap smallest and current index
        int tmp = *itr;
        *itr = smallest;
        smallest = tmp;
    }
}

int main()
{
    //create a list and some elements
    list<int> listi;
    listi.push_back(5);
    listi.push_back(4);
    listi.push_back(3);
    listi.push_back(2);
    listi.push_back(1);

    // sort the list
    sort_list(listi);
    //print all of the elements
    for(list<int> :: iterator itr = listi.begin(); itr != listi.end(); ++itr)
    {
            cout << *itr << endl;
    }

    return 0;
}

问题是你糟蹋itr在初始化itr2

When you do itr2 = ++itr you also change the value of itr , so instead you should do something like 当你做itr2 = ++itr你也改变了itr的值,所以你应该做类似的事情

list<int> :: iterator itr2 = itr;
for(++itr2; itr2 != a.end(); ++itr2) {
    ...
}

Furthermore, you have to keep a pointer to the smallest element, if you want to swap it later, like this: 此外,如果要稍后交换,则必须保留指向最小元素的指针,如下所示:

 int* smallest = &(*itr);

This also requires some other changes, you can find a working example of your code here . 这还需要进行一些其他更改,您可以在此处找到代码的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM