Win a copy of Functional Reactive Programming this week in the Other Languages forum!
    Bookmark Topic Watch Topic
  • New Topic

ArrayList sorting

 
Elvis Ve
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 12
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 7023
  • Mark post as helpful
  • send pies
  • Report post to moderator
I'm moving this to the Intermediate forum...
 
Nick George
Ranch Hand
Posts: 815
  • Mark post as helpful
  • send pies
  • Report post to moderator
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 ]
 
Dirk Schreckmann
Sheriff
Posts: 7023
 
    Bookmark Topic Watch Topic
  • New Topic