I've been working on code to sort integer in an array list, but my code is only returning only 2 numbers can anybody help me understand what I'm doing wrong here. How do I get all the numbers to be displayed? The numbers in my array
- ArrayList testNumbers = new ArrayList();
- testNumbers.add(48);
- testNumbers.add(3);
- testNumbers.add(23);
- testNumbers.add(99);
[48,3,23,99]. Any help would be greatly appreciated.
public ArrayList<Integer> listSort(ArrayList<Integer> numbers) {
// create variable to store max number
int maxNumber = 0;
// creates an array that will store the sorted numbers
ArrayList<Integer> sortedIntArray = new ArrayList<Integer>();
// loops through each number in the numbers arraylist
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) > maxNumber) {
// set the number to the new max number
maxNumber = numbers.get(i);
// add current max number to sorted array
sortedIntArray.add(maxNumber);
// remove the max number from numbers array
numbers.remove(numbers.get(i));
}
}
return sortedIntArray;
}
//the sortedIntArray returns [48,99]
i
. Grab paper and pen and draw this out and trace what happens. – JonH Jul 20 '11 at 17:26