Java Recursively Sort an ArrayList
Go to solution
Solved by Satlen,
Alright guys, I actually figured it out. I ended up not going with the merge sort because that was making things more complicated than they needed to be. I ended up using a much simpler sorting method which basically sets the the first value in a given range to the min and compares it to the rest, swaps the two elements if it finds a smaller one, then is recursively called until everything is sorted.
Here is a snippet of my method in case anyone is curious in the future:
private static void sortObjects(ArrayList<GeometricObject> list, int low, int high){ if (low < high){ int minIndex = low; GeometricObject min = list.get(low); //set min to first object in range for (int i = low + 1; i <= high; i++){ //loop through all values other than first if (list.get(i).getArea() < min.getArea()){ //check if the value is smaller than current min min = list.get(i); //if it is update the min minIndex = i; //store min index so we can swap locations later } } Collections.swap(list, low, minIndex); //move the original min to new min's old index (tricky wording) list.set(low, min); //set the old lowest to the new lowest using store min value sortObjects(list, low + 1, high); //call it again } }
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now