I have a problem with my code, I have made a singly linked list class in which you can add, remove, modify, merge etc... however, I am attempting a simple bubble sort and have come across problems in which the list is not correctly sorted. here are some things to note:
public static void sortList()
{
if (isEmpty() == true)
{
System.out.println("Cannot sort - the list is empty");
}
else if (getHead().getNext() == null)
{
System.out.println("List sorted");
}
else
{
Node current = getHead().getNext();
CustomerFile tempDat;
boolean swapDone = true;
while (swapDone)
{
current = getHead().getNext();
swapDone = false;
while (current != null)
{
if (current.getNext() != null &&
current.getData().getSurname().compareTo(
current.getNext().getData().getSurname()) >0)
{
tempDat = current.getData();
current.setData(current.getNext().getData());
current.getNext().setData(tempDat);
swapDone = true;
}
current = current.getNext();
}
}
if (getHead().getData().getSurname().compareTo(
getHead().getNext().getData().getSurname()) >0)
{
current = getHead().getNext();
getHead().setNext(current.getNext());
setHead(current);
}
}
}
I would appreciate the feedback
Your code is an odd mixture, mostly swapping data but treating the head specially trying to swap it with the next by switching the links.
As noted in another answer, this last swap is not correctly implemented, but really there's no reason to treat the head specially if you're doing things by swapping the data.
All you have to do is start each traversal of the list at the head in the outer loop.
This yields a working solution:
public void sortList()
{
if (isEmpty())
{
System.out.println("An empty list is already sorted");
}
else if (getHead().getNext() == null)
{
System.out.println("A one-element list is already sorted");
}
else
{
Node current = getHead();
boolean swapDone = true;
while (swapDone)
{
swapDone = false;
while (current != null)
{
if (current.getNext() != null && current.getData().getSurname().compareTo(current.getNext().getData().getSurname()) >0)
{
CustomerFile tempDat = current.getData();
current.setData(current.getNext().getData());
current.getNext().setData(tempDat);
swapDone = true;
}
current = current.getNext();
}
current = getHead();
}
}
}
I've made this non-static because as noted in comments it wasn't clear to me how yours could work as a static. You may be able to make it static in your context.
I also changed a couple other minor things. It's never necessary to check a condition by code like
if (isEmpty() == true)
In Java, this is entirely equivalent to
if (isEmpty())
And tempDat
doesn't need to be declared outside of where it's used.