Io ho cercato di suddividere prima la lista in due sottoliste,ordinarle e poi fonderle di nuovo insieme in un unica lista (cioè applicando la teoria su cui si basa questo tipo di ordinamento)
Questo è il codice:
codice:
public class Mergesort
{
public static Nodo head;
// Main
public static void main(String [] args)
{
int n[]={9,5,1,7,3,2,8,4,6,10};
Lista numeri = new Lista();
for(int i=0;i<n.length;i++)
numeri.insertHead(n[i]);
numeri.printList();
System.out.println("\n--Ordino la lista con Mergesort--");
splitList(numeri);
System.out.print("Lista ordinata: ");
numeri.printList();
}
public static void splitList(Lista outList2)
{
if(head != null && head.next != null)
{ // Inizializzazione
outList2.head = head.next;
head.next = head.next.next;
outList2.head.next = null;
// Richiamo metodo interno
splitListInternal(head.next,outList2.head);
}
}
private static void splitListInternal(Nodo inpFirst,Nodo outFirst)
{
if(inpFirst!= null && inpFirst.next != null)
{ // Spostamento riferimenti
outFirst.next = inpFirst.next;
inpFirst.next = inpFirst.next.next;
outFirst.next.next = null;
// Richiamo ricorsivo
splitListInternal (inpFirst.next, outFirst.next);
}
}
public void mergeList(Lista secondList)
{
if(head == null)
head = secondList.head;
else if(secondList.head != null)
{
if(((Comparable)secondList.head.info).compareTo(head.info)<0)
{
Nodo savElem = secondList.head.next;
secondList.head.next = head;
head = secondList.head;
secondList.head = savElem;
};
mergeListInternal(head,secondList.head);
}
}
private void mergeListInternal(Nodo firstElem,Nodo secondElem)
{
if(secondElem != null)
{
if(firstElem.next == null)
{ firstElem.next = secondElem; }
else
{
if(((Comparable)firstElem.next.info).compareTo(secondElem.info)>0)
{
Nodo savElem = secondElem.next;
secondElem.next = firstElem.next;
firstElem.next = secondElem;
secondElem = savElem;
}
mergeListInternal(firstElem.next,secondElem);
}
}
}
public void sortList()
{
if(head != null && head.next != null)
{
Lista otherList = new Lista ();
splitList(otherList);
sortList();
//otherList.sortList();
mergeList(otherList);
}
}
}
Spero che adesso qualcuno mi possa dare una mano. Ciao!