单向链表的选择排序

Selection Sort on a Singly Linked List

正如我检查的那样,我找到了正确的最小值和前一个节点。之后我唯一需要做的就是交换节点,但是在执行此代码后,输出什么也没有。

画完题我以为问题解决了part.So我又加了一个节点名字解决了还是没解决我的问题

这是我的示例代码:

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

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

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

通过 value/data 而不是节点交换大大简化了代码:

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