-2

I hope the title is not too misleading. I have two arrays, for example:

[9, 2, 5, 6, 3]
[1.0, 7.0, 4.0, 9.0, 8.0]

First of all I want to sort the first array ascending. Then I would like to apply the position changes to the second array, no matter if the sorting of the second array is correct.

So applied to the given example the result would be:

[2, 3, 5, 6, 9]
[7.0, 8.0, 4.0, 9.0, 1.0]

Alternatively it could also be a List instead of an array. Can someone help?

John
  • 795
  • 3
  • 15
  • 38

2 Answers2

0

You have to track the indices. The easiest way to do it, is to sort index numbers rather than values, but using the values of the first array for comparisons, then apply the order of the indices to the second array.

With Java 8, you can do it as follows:

int[]    iArray={9, 2, 5, 6, 3};
double[] dArray={1.0, 7.0, 4.0, 9.0, 8.0};

double[] result=
   // original indices: ascending numbers from 0 to array length
   IntStream.range(0, iArray.length)
   // sort using the values of the first array
  .boxed().sorted(Comparator.comparingInt(ix->iArray[ix]))
   // apply to the values of the second array
  .mapToDouble(ix->dArray[ix])
   // create a result array
  .toArray();
System.out.println(Arrays.toString(result));

For a pre-Java 8 solution, you may look here.

Community
  • 1
  • 1
Holger
  • 285,553
  • 42
  • 434
  • 765
0

I'd create a Bean to hold both values

public static class MyBean {
    int i;
    double d;

    // constructor
}

And a comparator

static final Comparator<MyBean> COMPARATOR = new Comparator<MyBean>() {
    public int compare(MyBean b1, MyBean b2) {
       return new Integer(b1.i).compareTo(b2.i);
    }
}

Then

MyBean[] beans = {
    new MyBean(10, 2.1),
    new MyBean(20, 2.2),
    new MyBean(5, 1.3)
};
Arrays.sort(beans, COMPARATOR);
for (MyBean bean : MyBeans) {
   // do whatever
}
lance-java
  • 25,497
  • 4
  • 59
  • 101