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