Home > DeveloperSection > Forums > Most efficient way to simultaneously sort three ArrayLists in Java
John Brown
John Brown

Total Post:6

Points:42
Posted on    December-15-2015 12:33 AM

 Java Java  Array List  Sorting 
Ratings:


 1 Reply(s)
 208  View(s)
Rate this:
I am three ArrayLists. One of Strings - names, and two of Integers - score and picture numbers. I want to sort them simultaneously by the players scores (from highest to lowest). Now i use a simple bubble sort, but i think it will not be efficient when the Lists will be bigger.

My code:
public class MyBubbleSort {
    public static void bubble_srt(List<Integer> score, List<String> name, List<Integer> pic) {
        int n = score.size();
        int k;
        for (int m = n; m >= 0; m--) {
            for (int i = 0; i < n - 1; i++) {
                k = i + 1;
                if (score.get(i) < score.get(k)) {
                    swapNumbers(i, k, score, name, pic);
                }
            }
            printNumbers(score);
        }
    }
    private static void swapNumbers(int i, int j, List<Integer> score, List<String> name, List<Integer> pic) {
        int temp;
        temp = score.get(i);
        score.set(i, score.get(j));
        score.set(j, temp);
        String s;
        s = name.get(i);
        name.set(i, name.get(j));
        name.set(j, s);
        int p;
        p = pic.get(i);
        pic.set(i, pic.get(j));
        pic.set(j, p);
    }
    private static void printNumbers(List<Integer> input) {
        for (int i = 0; i < input.size(); i++) {
            System.out.print(input.get(i) + ", ");
        }
        System.out.print("\n");
    }
}


Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Supported
Posted on    December-15-2015 12:40 AM

Best way would be to create a class containing score, name and pic properties and have a single List of that class, which you sort using Collections.sort and a Comparator that compares two instances of your class according to the score property.

Bubble sort is in-efficient compared to other sorting algorithms (merge sort, quick sort), and there's no need to implement a sort algorithm yourself, since the standard Java packages already do that for you.

Don't want to miss updates? Please click the below button!

Follow MindStick