I want to sort an ArrayList so that it is smallest to largest. I have the following code:
public static ArrayList<BigInteger> sortBigInteger(ArrayList<BigInteger> toSort){
ArrayList<BigInteger> toReturn = new ArrayList<BigInteger>();
toReturn.add(toSort.remove(0));
for (int i = 0; i < toSort.size(); i++){
BigInteger n = toSort.get(i);
boolean eval = false;
in: for (int a = 0; a < toReturn.size(); a++){
if (n.compareTo(toReturn.get(a)) < 0){
toReturn.add(a, toSort.remove(i));
eval = true;
break in;
}
}
if (!eval) toReturn.add(toSort.remove(i));
}
toSort = toReturn;
return toReturn;
}
However, I lose elements. With an ArrayList of size 32, I get an ArrayList of size 15. Where are the extra removes happening?
Main Question: How do you sort an ArrayList?
You can always use
Collections.sort(toSort)1.It will simply sort the ArrayList
toSort.Note – it is usually much better to use built in libraries, that are already built tested and optimized for you, rather then re-invent the wheel. The result in most cases is likely to :
P.S.
The reason your algorithm fails is that you are keep removing elements from
toSort, and then read from larger indices.For a short example, have a look on the list
[5,2,9].First you have
toSort = [5,2,9] , toReturn = []When
i == 0, you will basically invoke:toReturn.add(toSort.remove(0));It will result in the lists:
toSort = [2,9], toReturn = [5].But, on next iteration –
i==1, and you will check the element with index 1, which is now 9, not 2! You missed an element!(This is actually a good example why using a built in sort is usually better!)
(1) Assuming from your comments you only want to sort it, and not doing it as self improvement or task. If you are interested about sorting algorithms, you might find the wikipedia page on sorting algorithms helpful, especially the one that is actually used in java – TimSort.