Monday, 15 February 2010

java - How to sort an arraylist of numbers depending on size? -



java - How to sort an arraylist of numbers depending on size? -

edit: should have specified can't utilize built in sort algorithm this.

i have arraylist of rational numbers , want sort adding numbers in order of highest lowest new arraylist. @ moment output first rational number of arraylist. doing wrong , how can work?

public static collection<rational> sort(list<rational> list){ list<rational> sortedlist = new arraylist<rational>(); (iterator<rational> = list.iterator(); it.hasnext(); ) { rational currentvalue = it.next(); // sortedlist position currentvalue should go rational pos = null; (int i=0;i<sortedlist.size();i++) { // compare currentvalue sortedlist.get(i) // know if right position currentvalue. // if is, assign pos if(currentvalue.compareto(sortedlist.get(i)) > 0){ pos = (sortedlist.get(i)); } else if((currentvalue.compareto(sortedlist.get(i)) == 0)){ pos = (sortedlist.get(i)); } else if(currentvalue.compareto(sortedlist.get(i)) < 0){ pos = (sortedlist.get(i)); } } sortedlist.add(pos); } homecoming sortedlist; }

edit: corrected j in inner loop

the previous answers provide "the best" way go this. however, if you'd know how prepare original take on problem, here's way create original code work wanted work. changed iterator index syntax both lists handled same way more readable code. other way go have been create sortedlist utilize iterator. if you'd alter comparing > 0 comparing < 0, you'd reverse order.

public static collection<rational> sort(list<rational> list){ list<rational> sortedlist = new arraylist<rational>(); (int i=0;i < rationallist.size();i++) { rational currentvalue = rationallist.get(i); int pos = sortedlist.size(); // default end of list (int j=0;j<sortedlist.size();j++) { int comparing = currentvalue.compareto(sortedlist.get(j)) //this right position if currentvalue greater or equal //to sorted value @ position if(comparison > 0 || comparing == 0){ pos = j; break; } } sortedlist.add(pos, currentvalue); } homecoming sortedlist; }

the problems original code were:

1) weren't looking int index value of right position, had rational position, feels bit weird 2) in sortedlist check phase, called pos = (sortedlist.get(i)); no matter comparing 3) added value of pos sortedlist: sortedlist.add(pos);

so corrections were:

1) looking int index value of right position in current sortedlist 2) interested in position, new value either greater or equal current sorted value @ position 3) set currentvalue sortedlist specific index found comparison. default position @ end.

java

No comments:

Post a Comment