The Artima Developer Community
Sponsored Link

Java Answers Forum
Sorting a linked list

1 reply on 1 page. Most recent reply: Feb 11, 2003 9:29 PM by David Resseguie

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Adrian

Posts: 1
Nickname: watts
Registered: Feb, 2003

Sorting a linked list Posted: Feb 8, 2003 11:42 AM
Reply to this message Reply
Advertisement
Can someone help me with my sort method?

public LinkedList sort(LinkedList unsorted){

if(unsorted == null)throw new IllegalArgumentException("unsorted LinkedList cannot be null");
if(unsorted.isEmpty() == true)throw new IllegalArgumentException("cannot sort an emty list");
//private temp varianles
LinkedList sortedList = new LinkedList();
LinkedListIterator cursor1 = unsorted.zeroth();
LinkedListIterator cursor2 = unsorted.first();
cursor1.advance();
cursor2.advance();
Comparable maxStud = null;
Comparable nextStud;
while(unsorted.isEmpty() != true){
while(cursor2.isValid() == true){
maxStud = (Comparable)cursor1.retrieve();
nextStud = (Comparable)cursor2.retrieve();
if((maxStud.compareTo(nextStud)) == 0){
System.out.println("comparing: "+maxStud+" with :"+nextStud);
//they are both the same, advance cursor1
cursor2.advance();
}
else if((maxStud.compareTo(nextStud))==1){
System.out.println("comparing: "+maxStud+" with :"+nextStud);
//item is larger
cursor1= cursor2;
cursor2.advance();
}
else if((maxStud.compareTo(nextStud))==-1){
System.out.println("comparing: "+maxStud+" with :"+nextStud);
cursor2.advance();
}


}
//if(cursor2.isValid() == false){
sortedList.insert(maxStud,sortedList.zeroth());//need to see how ti find the previos
System.out.println("max student was: "+maxStud);
unsorted.remove(maxStud);
//System.out.println("sorted list:");
//printList(unsorted);
cursor1 = unsorted.zeroth();
cursor2 = unsorted.first();
cursor1.advance();
cursor2.advance();
//}
}
return sortedList;

}


David Resseguie

Posts: 5
Nickname: dressegu
Registered: Feb, 2003

Re: Sorting a linked list Posted: Feb 11, 2003 9:29 PM
Reply to this message Reply
Sounds like a school project?

Here's a link to Weiss's book on data structures and algorithms in Java. In particular, there is sample source code that can be downloaded (the examples from the book). There is a file called Sort.java I think that has several static sorting methods that act on arrays. You may use them for guidance to sort a List.

http://www.cs.fiu.edu/~weiss/dsaajava/code/

David

Flat View: This topic has 1 reply on 1 page
Topic: how to open new window Previous Topic   Next Topic Topic: Unicode & JDBC-ODBC Bridge

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use