Brij Raj Kishore - 6 months ago 34

Java Question

I have 3 arrays

a[n] , b[n] ,c[n]

a and b arrays are entered by the user and c is calculated as

c[i] = b[i] - a[i] + 1

Sorting the c array is easy. I sorted it by

Arrays.sort(c) method

Now I have to sort arrays a & b according to c as follows

For Example -

a[5] ={1 , 3 , 5 , 7 , 9 }

b[5] ={5 , 4 , 7 , 8 , 10 }

Then c[] will be calculated as

c[i] = b[i] - a[i] +1.

c[5] ={5 , 2 , 3 , 2 , 2}

Now sorting the c array results in

c[5] = { 2 , 2 , 2 , 3 , 5 }

Now I also want a[i] and b[i] as

a[5]={ 3 , 7 , 9 , 5 , 1 }

b[5]={ 4 , 8 , 10 , 7 , 5 }

such that the now the relationship between arrays will be maintained

for each element 'i'

c[i] = b[i] - a[i] + 1

Answer

Using array will be way too messy. You can keep them in a class:

```
public class Triplets {
public int a;
public int b;
public int c;
}
```

Then we can take input in this class instead of seperate arrays (for example) :

```
int [] a ={1 , 3 , 5 , 7 , 9 };
int [] b ={5 , 4 , 7 , 8 , 10 };
Triplets [] tripletses = new Triplets[5];
for (int i = 0 ; i < tripletses.length ; i++){
tripletses[i] = new Triplets();
tripletses[i].a = a[i];
tripletses[i].b = b[i];
tripletses[i].c = tripletses[i].b - tripletses[i].a + 1;
}
```

Of course you need to use your own input logic there. Now we can sort this array using a Custom Comparator

```
Arrays.sort(tripletses, new TripletsComp());
```

And of course the Comparator:

```
public class TripletsComp implements Comparator<Triplets> {
@Override public int compare(Triplets e1, Triplets e2) {
if(e1.c > e2.c){
return 1;
}else if (e1.c == e2.c){
return 0;
}
else { return -1; }
}
}
```

If you are not familiar with Comarator, have a read about them :)