• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to display a sorted list after sorting.  RSS feed

 
Sunali Anu
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method which sorts the Array list by the Item Id. I am trying to print out the same after sorting, but my code doesn't seem to do anything. Not sure if the code is wrong or i am not knowing what to display after sorting. Should i create a new Arraylist to store the swapped and sorted values and then display that??

Please take a look at the code below:
Code:
---------------------------------------------------------------------------
public static void sortItemNum(ArrayList<Item> itm)
{
System.out.println("The records sorted by Item Number:");

for(int out=itm.size()-1; out>1; out--)
{// outer loop (backward)
for(int in=0; in<out; in++)
{// inner loop (forward)
if( itm.get(0).getItem().getId() > itm.get(1).getItem().getId() ) // out of order?
swap(itm.get(0).getItem().getId(), itm.get(1).getItem().getId()); // swap them

}

}

for(int k=0; k<itm.size(); k++)
{
System.out.println(insure.get(k));
}

}
private static void swap(int one, int two)
{
int temp = one;
one = two;
two = temp;
}
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37513
554
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sunali,
Your swap method doesn't do what you think it does. See this thread for the reasons why.
 
Remko Strating
Ranch Hand
Posts: 893
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you use the Arrays.sort method.

In which you can define a Comparator which sortes your Items by itemnumber

The following link will guide you

Why you shouldn't write your own sort
 
Sunali Anu
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I used Collections.swap method and that worked.. Thanks for the posts..
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!