Reputation: 70
i made the linked list its not from java collections and i put in it many methods .. my linked list worked like the original one but theres a small differences my class have a print and sort methods my input is : [5,18,3,10,2] ... or it can be a string inputs .. i want the sort method to sort the linked list , so the output should be like this : [2,3,5,10,18] or a sorted string here is the sort method code :
public void sort(){
Node<E> current = head ;
Node<E> current2 = current.next;
E min = head.element;
E temp;
int pos = 0;
for (int i = 0; i < size-1; i++) {
for (int j = 0; j < size; j++) {
if(current2 != null){
if(min.compareTo(current2.element) > 0){
pos = j ;
min = current2.element;
}
current2= current2.next;
}
}
temp = current.element;
current.element = min;
current = current.next;
min = current.element;
current2 = head;
for (int j = 0; j <= pos; j++) {
if(current2 !=null){
if(j==pos){current2.element = temp;}
current2= current2.next;
}
}
current2 = current.next;
}
}
Upvotes: 0
Views: 108
Reputation: 845
Try with this sort method.
public void sort()
{
for (int i = size - 1; i >= 1; i--)
{
Node<E> finalNode = head;
Node<E> tempNode = head;
for (int j = 0; j < i; j++)
{
E val1 = head.element;
Node<E> nextnode = head.next;
E val2 = nextnode.element;
if (val1.compareTo(val2))
{
if (head.next.next != null)
{
Node<E> CurrentNext = head.next.next;
nextnode.next = head;
nextnode.next.next = CurrentNext;
if (j == 0)
{
finalNode = nextnode;
}
else
head = nextnode;
for (int l = 1; l < j; l++)
{
tempNode = tempNode.next;
}
if (j != 0)
{
tempNode.next = nextnode;
head = tempNode;
}
}
else if (head.next.next == null)
{
nextnode.next = head;
nextnode.next.next = null;
for (int l = 1; l < j; l++)
{
tempNode = tempNode.next;
}
tempNode.next = nextnode;
nextnode = tempNode;
head = tempNode;
}
}
else
head = tempNode;
head = finalNode;
tempNode = head;
for (int k = 0; k <= j && j < i - 1; k++)
{
head = head.next;
}
}
}
}
Upvotes: 1