简体   繁体   English

在单链表上实现选择排序

[英]Implementing selection sort on a singly linked list

Heya I'm trying to implement selection sort algorithm on a singly linked list , I'm aware that there is some problem in the code but although My linked list includes the numbers 7 1 2 6 the output after running is 7777 . 嘿,我试图在单链表上实现选择排序算法,我知道代码中存在一些问题,但是尽管我的链表包含数字7 1 2 6,但运行后的输出为7777。 Any help would be appreciated. 任何帮助,将不胜感激。

template<class Type>
void UnOrderedLinkedList<Type>::selectionSort()
{
nodeType<Type>* loc;
nodeType<Type>* minIndex;
nodeType<Type>* temp;
temp = first;
if(temp == NULL)
    cerr<<"Cannot sort an empty list."<<endl;
else
    if(temp->link == NULL)
    cerr<<"List has only one item so it is already sorted."<<endl;
else

while(temp != NULL)
{
    minIndex = minLocation(temp, last);
    swap(temp, minIndex);
    temp = temp->link;
}
}


template<class Type>
nodeType<Type>* UnOrderedLinkedList<Type>::minLocation(nodeType<Type>* first, nodeType<Type>* last)

nodeType<Type>* minIndex;
nodeType<Type>* other;

minIndex = first;
other = minIndex->link;

while(other != NULL)
{
    if(minIndex->info > other->info)
    {
        minIndex = other;
        other = other->link;
    }

    else
    {
        other = other->link;
    }

}
    return minIndex;
}

Then to swap: 然后交换:

template<class Type>
void UnOrderedLinkedList<Type>::swap(nodeType<Type>* first, nodeType<Type>* second)
{
     nodeType<Type>* temp;
     temp->info = first->info;
     first->info = second->info;
     second->info = temp->info;
}

From your swap function: 通过swap功能:

 nodeType<Type>* temp;
 temp->info = first->info;

That is a clear case of undefined behavior ! 那显然是未定义行为的情况 You declare a local variable, a pointer, without initialization. 您声明局部变量,即指针,而无需初始化。 Then you directly uses the uninitialized variable, leading to said UB. 然后,您直接使用未初始化的变量,导致所说的UB。 Since you use pointers, you should actually be happy that the program didn't crash. 由于使用了指针,因此您应该对程序没有崩溃感到满意。

Here you don't need a pointer or a node as you don't actually swap nodes. 在这里,您不需要指针或节点,因为您实际上并不交换节点。 All you need is an instance of what info is, and use that: 您所需要的只是一个info实例,并使用该实例:

SomeType temp;
temp = first->info;
first->info = second->info;
second->info = temp;

The answer by @JoachimPileborg works of course, but note that you don't need to write a member function sort of your own singly linked list in order to do selection sort. @JoachimPileborg的答案当然有用,但是请注意,您不需要为自己的单链表编写成员函数sort即可进行选择排序。

The reason is that a generic version of selection_sort (with O(N^2) complexity) is already compatible any singly linked list that exposes forward iterators , such as the one from the Standard Library, std::forward_list : 原因是selection_sort (具有O(N^2)复杂度)的通用版本已经兼容任何公开前向迭代器的单链列表,例如标准库std::forward_list

#include <algorithm>    // min_element, iter_swap, is_sorted
#include <cassert>      // assert
#include <forward_list> // forward_list
#include <functional>   // less
#include <iostream>     // cout
#include <ios>          // boolalpha
#include <iterator>     // distance, next

template<class FwdIt, class Compare = std::less<>>
void selection_sort(FwdIt first, FwdIt last, Compare cmp = Compare{})
{
    for (auto it = first; it != last; ++it) {
        auto const selection = std::min_element(it, last, cmp);
        std::iter_swap(selection, it); 
        assert(std::is_sorted(first, std::next(it), cmp));
    }
}

int main()
{
    auto fl = std::forward_list<int> { 2, 4, 1, 0, -1, 8, 2 };
    std::cout << std::boolalpha << std::is_sorted(fl.begin(), fl.end()) << '\n';
    for (auto const& e : fl) std::cout << e << ", "; std::cout << '\n';
    selection_sort(fl.begin(), fl.end());
    std::cout << std::boolalpha << std::is_sorted(fl.begin(), fl.end()) << '\n';
    for (auto const& e : fl) std::cout << e << ", "; std::cout << '\n';
}

Live Example 现场例子

Note that std::forward_list also implements its own member function sort . 注意std::forward_list也实现了自己的成员函数sort This version -which does an O(N log N) merge sort- can not be implemented based on the public interface alone (actually you can, but with O(N) extra storage instead of the O(1) storage that forward_list guarantees). 此版本O(N log N)执行O(N log N)合并排序O(N log N)不能仅基于公共接口来实现(实际上可以,但是可以使用O(N)额外的存储空间,而不是forward_list保证的O(1)存储空间) 。

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

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