选择按单链接列表排序

时间:2016-11-06 07:42:40

标签: c# singly-linked-list selection-sort

在检查时,我找到了正确的最小值和上一个节点。在那之后,我唯一需要做的就是交换节点,但是在实现这段代码之后输出就没什么了。

在绘制问题之后,我认为问题是排序的部分。所以我又添加了一个节点,该节点的名称已经排序但仍然无法解决我的问题。

这是我的示例代码:

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;
        }            
    }

1 个答案:

答案 0 :(得分:0)

我将代码中的一些变量重命名为更有意义的变量:

  • currentOuter跟踪外部循环中的当前节点
  • currentInner跟踪内循环中的当前节点

按值/数据而不是节点进行交换简化了代码:

public void selectionSort<T>(Node<T> head) where T:IComparable
{
    Node<T> currentOuter = head;

    while (currentOuter != null)
    {
        Node<T> minimum = currentOuter;
        Node<T> currentInner = currentOuter.Next;

        while (currentInner != null)
        {
            if (currentInner.Value.CompareTo(minimum.Value) < 0)
            {
                minimum = currentInner;
            }

            currentInner = currentInner.Next;
        }

        if (!Object.ReferenceEquals(minimum, currentOuter))
        {
            T temp = currentOuter.Value;
            currentOuter.Value = minimum.Value;
            minimum.Value = temp;
        }

        currentOuter = currentOuter.Next;
    }
}