So I'm playing around with a number-sorting program, trying to write the most efficient way possible to order a random list of numbers from lowest to highest.
I'm having trouble after the first number sorting method has been run, the ArrayList passed to the second method is empty. I figure it has something to do with the first methods sorting technique; which finds the lowest value, places it in a new ArrayList, removes it from the mixed one, then starts again.
What I don't understand is that I pass the mixedArray to sortingMethod1, which is in an entirely different class, yet somehow it still edits the local variable in the main method... help please?
P.S. All of this uses ArrayLists, even though I reference array.
Inside The Main Method:
List<Integer> mixedArray = sorter.generateNumbers(numbers, range);
sorter.printArray(mixedArray); //The Random Numbers
sorter.printArray(sorter.sortingMethod1(mixedArray)); //This prints them out ordered
sorter.printArray(sorter.sortingMethod2(mixedArray)); //This receives a null array
Here is sortingMethod1:
public List<Integer> sortingMethod1(List<Integer> mixedArray){ //Finds the lowest, places it into a new array.
List<Integer> sortedArray = new ArrayList<Integer>();
while (!mixedArray.isEmpty()) {
int lowest = mixedArray.get(0);
for (int i = 1; i < mixedArray.size(); i++) {
if (mixedArray.get(i) < lowest) {
lowest = mixedArray.get(i);
}
}
sortedArray.add(lowest);
mixedArray.remove(mixedArray.indexOf(lowest));
}
return sortedArray;
As requested, sortingMethod2, however it is still untested
public List<Integer> sortingMethod2 (List<Integer> mixedArray) { // Finds the lowest, places it at beginning
for (int i = 0; i < mixedArray.size(); i++) {
int lowest = mixedArray.get(i);
for (int x = i; x < mixedArray.size(); x++) {
if (mixedArray.get(x) < lowest) {lowest = mixedArray.get(x);}
}
Collections.swap(mixedArray, i, mixedArray.indexOf(lowest));
}
return mixedArray;
}