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;
}
});
You can declare a Pair
like this:
static class Pair {
double a;
double b;
Pair(double a, double b) {
this.a = a;
this.b = b;
}
}
and put arrays into an array of pairs. Then it's easy to sort them:
Pair[] p = new Pair[a.length];
for (int i = 0; i < p.length; i++)
p[i] = new Pair(a[i], b[i]);
Arrays.sort(p, (p1, p2) -> Double.compare(p1.a/p1.b, p2.a/p2.b));
Of course, the results are in the new array. You can loop and put them back to a
and b
if you want.
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]];
}
Let us see an example first:
Question: Which is the larger among the two? 8/6
or 9/7
?
Answer: An easy way is to do the following for any two numbers of the form a/b
and c/d
. Find a*d
and b*c
. If a*d
is bigger then a/b
is greater than c/d
, otherwise c/d
is greater.
According to the example: 8*7=56
>
9*6=54
, hence 8/6
is greater than 9/7
.
So, use the above logic in the Comparator .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.