wood burning stoves 2.0*
The moose likes Java in General and the fly likes ArrayList sorting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

ArrayList sorting

Elvis Ve
Greenhorn

Joined: May 17, 2004
Posts: 19
im having a problem sorting the ArrayList using selection sort, just need help in the swap method.

void Sort()
{
int length = list.size();
for(int i = 0; i < length -1;i++)
{
int index = findPosition(i);
swap(index,i);
}

}

void swap(int startScan, int i)
{



}


int findPosition(int i)
{
int startScan = 1;
Student s = (Student)list.get(i);
for(int k =0; i < list.size()-1;i++)
{
Student d = (Student)list.get(k);
if(d.getLname().compareTo(s.getLname())< 0);

}
return startScan;
}
Jeffrey Bennett
Greenhorn

Joined: May 17, 2004
Posts: 12
What are you trying to accomplish?

In general, if you have an unsorted Collection that you wish to sort, utilize a Comparator and one of the sortable portions of the Collections framework, TreeSet works well.

This is off the top of my head, it may not compile, but you get the idea...

Collection coll = ...your array list for example...
class MyComparator implements Comparator
{
int compare(Object o1, Object o2)
{
return ((Student) o1).getLname().compareTo(((Student)o2).getLname());
}
}
TreeSet tset = new TreeSet(new MyComparator());
tset.addAll(coll);

Iterating tset will now yield the Collection in sorted order.
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
I'm moving this to the Intermediate forum...


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Nick George
Ranch Hand

Joined: Apr 04, 2004
Posts: 815
As far as I can tell, the problem with 'swap' stems from the fact that it is somewhat empty. If all you want to do is swap two objects at two indicies in the list, the form is rather simple:




[ May 22, 2004: Message edited by: Joseph George ]

I've heard it takes forever to grow a woman from the ground
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Please continue in the duplicate thread.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ArrayList sorting
 
Similar Threads
Help with array List
I am getting "void type not allowed here" error
Sorting the String Saved in ArrayList
ArrayList
remove the element in list while iterating through it.