bubble sort implementation on linked lists

后端 未结 6 1413
小蘑菇
小蘑菇 2020-12-11 14:06

I have to implement a BubbleSort algorithm on a Linked List instead of an array. I\'m new to java so I don\'t really know how to put it in code. But I gave it a try and here

6条回答
  •  轮回少年
    2020-12-11 14:07

    Example linked list bubble sort that doesn't emulate random access using an elementAt() function, and instead operates via the links between nodes, so time complexity is O(n^2) instead of being much worse. "end" is used to keep track of where the sorted nodes at the end of the list begin. I used the example code from the question and didn't bother changing the class to comparable, using toString() instead for the compare. I used a dummy node to simplify the code.

    void bubbleSort()
    { 
        if(first == null)
            return;
        SinglyNode dmy = new SinglyNode("dummy");  // dummy node
        dmy.next = first;
        // end == null or first sorted node at end of list
        SinglyNode end = null;
        int swap;
        do{
            swap = 0;
            SinglyNode prv = dmy;           // previous node
            while(true){
                SinglyNode cur = prv.next;  // current node
                SinglyNode nxt = cur.next;  // next node
                if(nxt == end){             // if at end node
                    end = cur;              //  update end = cur
                    break;                  //  and break
                }
                // if out of order, swap nodes
                if(cur.names.toString().compareTo(nxt.names.toString()) > 0){
                    cur.next = nxt.next;
                    nxt.next = cur;
                    prv.next = nxt;
                    swap = 1;
                }
                prv = prv.next;             // advance to next node
            }
        }while(swap != 0);                  // repeat untl no swaps
        first = dmy.next;                   // update first
    }
    

提交回复
热议问题