LED Fantom LED Fantom - 2 months ago 12
Java Question

How to sort two arrays based on ratio in Java?

I'd like to sort 2 arrays based on the ratios of their matching indices. So based on the ratio of a[x]/b[x], a[] and b[] are sorted accordingly. Here is the basic structure:

double[] a = {60.0, 100.0, 120.0};
double[] b = {20.0, 50.0, 30.0};

r0 = a[0]/b[0]
r1 = a[1]/b[1]
r2 = a[2]/b[2]
...


The Java code I'm working on doesn't work. Could someone give me some help?

Arrays.sort(ratio, new Comparator<double[]>() {
@Override
public double compare(double[] a, double[] b) {
double r1 = (double)a[i]/b[i];
double r2 = (double)a[i+1]/b[i+1];
return r1 > r2;
}

});

Answer

Try this.

double[] a = new double[10];
double[] b = new double[10];
// fill data to a and b.
int[] indexes = IntStream.range(0, a.length)
    .boxed()
    .sorted((i, j) -> Double.compare(a[i] / b[i], a[j] / b[j]))
    .mapToInt(i -> i)
    .toArray();
double[] sortedA = IntStream.of(indexes)
    .mapToDouble(i -> a[i])
    .toArray();
double[] sortedB = IntStream.of(indexes)
    .mapToDouble(i -> b[i])
    .toArray();

If you do not use Java8.

double[] a = new double[10];
double[] b = new double[10];
// fill data
int length = a.length;
Integer[] indexes = new Integer[length];
for (int i = 0; i < length; ++i)
    indexes[i] = i;
Arrays.sort(indexes, new Comparator<Integer>() {
    @Override public int compare(Integer o1, Integer o2) {
        return Double.compare(a[o1] / b[o1], a[o2] / b[o2]);
    }
});
double[] sortedA = new double[length];
double[] sortedB = new double[length];
for (int i = 0; i < length; ++i) {
    sortedA[i] = a[indexes[i]];
    sortedB[i] = b[indexes[i]];
}
Comments