Heya我正在尝试在单链表上实现选择排序算法,我知道代码中存在一些问题但是虽然我的链表包含数字7 1 2 6,但运行后的输出是7777 . 任何帮助,将不胜感激 .
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;
}
然后交换:
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;
}
2 回答
从
swap
函数:这是未定义行为的明显案例!你声明一个局部变量,一个指针,没有初始化 . 然后你直接使用未初始化的变量,导致所述UB . 既然你使用指针,你应该很高兴程序没有崩溃 .
在这里,你实际上不需要交换节点 . 您所需要的只是
info
的实例,并使用:@JoachimPileborg的答案当然有效,但请注意,您不需要编写自己的单链表的成员函数
sort
来进行选择排序 .原因是generic version(具有
O(N^2)
复杂性)已经兼容任何暴露 forward iterators 的单链表,例如标准库中的那个,std::forward_list
:Live Example
注意
std::forward_list
也实现了自己的成员函数sort
. 这个版本 - 它进行O(N log N)
合并排序 - 无法单独基于公共接口实现(实际上你可以使用O(N)
额外的存储而不是forward_list
保证的O(1)
存储) .