I have written a bubble sort algorithm to sort a linked list. I am a Java beginner and trying to learn data structures. I am confused why my second element is not sorted properly.
EDIT
class SListNode {
Object item;
SListNode next;
SListNode(Object obj) {
item = obj;
next = null;
}
SListNode(Object obj, SListNode next) {
item = obj;
this.next = next;
}
}
public class SList {
private SListNode head;
private SListNode temp;
public void sortList() {
SListNode node = head,i,j;
head = node;
i = node;
j = node.next;
while(i.next != null) {
while(j.next != null) {
if((Integer)i.item < (Integer)j.item) {
temp = i.next;
i.next = j.next;
j.next = temp;
}
j = j.next;
}
i = i.next;
}
}
}
This is the output I am getting
List after construction: [ 3 6 9 4 12 15 ]
After sorting: [ 3 4 9 12 6 15 ]
Besides I know the worst case scenario of a bubble sort is O(n2). Can I use mergesort on a linked list to have a better time complexity?
Thanks!