I need to write a method to sort an ArrayList in increasing order without using any built-in libraries or methods (not including java.util.ArrayList
, which may be used to allow ArrayLists, but for nothing else). I have my near complete code below, but the .remove()
function does not seem to be working; it does nothing, and the ArrayList ends up as the smallest element repeated for the entire size of the ArrayList. I tried replacing the while loop with a for loop with the update segment being tempDataCopy.remove(smallestElementIndex)
but it gave multiple errors, saying that the .remove() function has an "unknown source". How do I fix this?
public static ArrayList<Integer> sortUp(ArrayList<Integer> data) {
ArrayList<Integer> increasingArray = new ArrayList<Integer>();
ArrayList<Integer> tempDataCopy = data;// tempDataCopy was created so that elements may be deleted without affecting the actual ArrayList data
int smallestElement = tempDataCopy.get(0);
int smallestElementIndex = 0;
while (tempDataCopy.size() > 0) {
for (int i = 0; i < tempDataCopy.size(); i++) {
if (tempDataCopy.get(i) < smallestElement) {
smallestElement = tempDataCopy.get(i);
smallestElementIndex = i;
} // end if statement
} // end for loop
increasingArray.add(smallestElement);
tempDataCopy.remove(smallestElementIndex);
} // end while loop
return increasingArray;
}// end sortUp
Sorry if this is a duplicate, I searched for hours and could not find another example of similar sorting.