Search code examples
c#singly-linked-listselection-sort

Selection Sort on a Singly Linked List


As I checked, I find the right minimum value and previous node. After that the only thing I need to do is swapping nodes,however after implementing this code the output is nothing.

After drawing the question I thought the problem is sorted part.So I added one more node which name is sorted but still I couldn't solve my problem.

Here is my example code:

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

Solution

  • I renamed some variables in your code to more meaningful ones:

    • currentOuter tracks the current node in the outer loop
    • currentInner tracks the current node in the inner loop

    Swapping by value/data instead of by nodes simplifies the code a lot:

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