Sorting two arrays simultaneously

Below is the code without using any Map Collection, but if you want to use Map then it becomes very easy. Add both the arrays into map and sort it.

public static void main(String args[]) {
    String a[] = new String[] {
        "Sam", "Claudia", "Josh", "Toby", "Donna"
    };
    int b[] = new int[] {
        1, 2, 3, 4, 5
    };
    for (int n = 0; n < 5; n++) {
        System.out.print(a[n] + "...");
        System.out.println(b[n]);
    }
    System.out.println(" ");
    //java.util.Arrays.sort(a);
    /* Bubble Sort */
    for (int n = 0; n < 5; n++) {
        for (int m = 0; m < 4 - n; m++) {
            if ((a[m].compareTo(a[m + 1])) > 0) {
                String swapString = a[m];
                a[m] = a[m + 1];
                a[m + 1] = swapString;
                int swapInt = b[m];
                b[m] = b[m + 1];
                b[m + 1] = swapInt;
            }
        }
    }
    for (int n = 0; n < 5; n++) {
        System.out.print(a[n] + "...");
        System.out.println(b[n]);
    }
}

Some people propose making a product type. That is feasible only if the amount of elements is small. By introducing another object you add object overhead (30+ bytes) for each element and a performance penalty of a pointer (also worsening cache locality).

Solution without object overhead

Make a third array. Fill it with indices from 0 to size-1. Sort this array with comparator function polling into the array according to which you want to sort.

Finally, reorder the elements in both arrays according to indices.

Alternative solution

Write the sorting algorithm yourself. This is not ideal, because you might make a mistake and the sorting efficiency might be subpar.


You have to ZIP your two arrays into an array which elements are instances of a class like:

class NameNumber 
{

    public NameNumber(String name, int n) {
        this.name = name;
        this.number = n;
    }

    public String name;
    public int number;
}  

And sort that array with a custom comparator.

Your code should be something like:

NameNumber [] zip = new NameNumber[Math.min(a.length,b.length)];
for(int i = 0; i < zip.length; i++)
{
    zip[i] = new NameNumber(a[i],b[i]);
}

Arrays.sort(zip, new Comparator<NameNumber>() {

    @Override
    public int compare(NameNumber o1, NameNumber o2) {
        return Integer.compare(o1.number, o2.number);
    }
});