Java – What is the most efficient way to sort three ArrayLists at the same time in Java

What is the most efficient way to sort three ArrayLists at the same time in Java… here is a solution to the problem.

What is the most efficient way to sort three ArrayLists at the same time in Java

I have three ArrayLists. One in Strings – the name, and two in Integers – fraction and image number. I want to sort players by score (highest to lowest) at the same time. Now I’m using a simple bubbling sort, but I don’t think it works when Lists get bigger.

Here is 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");
    }

}

Thanks!

Solution

The best approach is to create a class that contains the score, name, and picture properties, and have a list of that class, and you can use Collections.sort and a Comparator to compare two instances of your class based on the score attribute.

Bubbling sorting is inefficient compared to other sorting algorithms (merge sort, quick sort), and you don’t need to implement the sorting algorithm yourself because the standard Java package already does it for you.

Related Problems and Solutions