I have a LinkedList that needs to be sorted (it contains ints), and i don’t know how to do that. Can anyone give my the source code to sort an int Linked List?
i tried this code which i found online but it didn’t work.
public void sort(LinkedList sortlist)
{
//Enter loop only if there are elements in list
boolean swapped = (head != null);
// Only continue loop if a swap is made
while (swapped)
{
swapped = false;
// Maintain pointers
Node curr = head;
Node next = curr.link;
Node prev = null;
// Cannot swap last element with its next
while (next != null)
{
// swap if items in wrong order
if (curr.data>next.data)
{
// notify loop to do one more pass
swapped = true;
// swap elements (swapping head in special case
if (curr == head)
{
head = next;
Node temp = next.link;
next.link = curr;
curr.link = temp;
curr = head;
}
else
{
prev.link = curr.link;
curr.link = next.link;
next.link = curr;
curr = next;
}
}
// move to next element
prev = curr;
curr = curr.link;
next = curr.link;
}
}
}
There is a C++ implementation of merge sort on linked lists given in this handout for Stanford’s CS106B course. It runs in time O(n log n), which is quite good.
For a survey of other approaches, check out this older SO answer on how to sort linked lists. There’s no code there, but there are good descriptions of how to adapt existing ideas to work on linked lists.
Hope this helps!