Search code examples
javalinked-listbubble-sortsingly-linked-list

Singly Linked List bubble sort


I have implemented Singly linked list in my code and i have to sort the list. But my code does not work, it stucks in an infinite loop. I have to compare nodes according to their id in ascending order.

I cant use arrays. This is my SLL node implementation.

  class SLLNode implements Comparable<SLLNode> {
    protected int id;
    protected int plata;
    protected SLLNode succ;

    public SLLNode(int id,int plata, SLLNode succ) {
        this.id = id;
        this.plata=plata;
        this.succ = succ;
    }

    @Override
    public int compareTo(SLLNode o) {
        return o.id - this.id;
    }
}

public static void sort(SLL lista){
    SLLNode current;
    boolean check = true;
    while(check) {
        current = lista.getFirst();
        check = false;

        while(current.succ != null)
        {
            if(current.compareTo(current.succ) > 0)
            {
                SLLNode temp = current;
                current=current.succ;
                current.succ=temp;
                check = true;
            }
            current = current.succ;
        }
    }
}

Solution

  • You problem is here:

                // Take a copy of current.
                SLLNode temp = current;
                // Step to next.
                current=current.succ;
                // Point temp (old current) to new next <----- Added this.
                temp.succ = current.succ;
                // Point next's successor to current.
                current.succ=temp;
                // Remember to check again.
                check = true;
    

    You are missing changing temp.succ. You need to set it to current.succ at the appropriate place.

    In summary - to swap two nodes a and b you need to do the following:

    • Set a.succ = b.succ <--- You missed this.
    • Set b.succ = a

    Without sample implementation of your linked list I cannot test this.