【发布时间】:2017-03-19 17:28:46
【问题描述】:
当我检查时,我找到了正确的最小值和前一个节点。之后我唯一需要做的就是交换节点,但是在执行此代码后,输出什么都没有。
画完问题后,我认为问题是已排序的部分。所以我又添加了一个名称已排序的节点,但我仍然无法解决我的问题。
这是我的示例代码:
public void selectionSort()
{
Node<T> first = head;
Node<T> previous = head;
Node<T> minimum = head;
Node<T> compare;
Node<T> temp;
Node<T> sorted = head;
while (first.Next != null)
{
sorted = minimum; // with this I'm finding the last sorted node
minimum = first;
compare = first.Next;
while (compare.Next != null)
{
if (minimum.Value.CompareTo(compare.Next.Value) > 0)
{
previous = compare; // Need previous node to changing connections
minimum = compare.Next; // Saving minimum value
}
compare = compare.Next;
}
// Swapping nodes
temp = first;
previous.Next = first;
first.Next = minimum.Next;
minimum.Next = temp.Next;
if ( temp != head)
{
sorted.Next = minimum; // Adding minimum node to sorted part
}
first = first.Next;
}
}
【问题讨论】:
标签: c# singly-linked-list selection-sort