Brij Raj Kishore - 1 year ago 53

Java Question

I have 3 arrays

a , b ,c

of size 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 have done it by

Arrays.sort(c)

but i want to make amends in a and b also such that the a[i] and b[i] corresponds to the new sorted c[i].

For Example -

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

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

Then

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

Now sorting the c array, it results in

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

Now i also want a and b as

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

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

Answer Source

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 :)