Reputation: 1
I want to sort an array, the problem is that each element of the array has certain values in another array for example first array={31,12,88,74,55} Second array={5,2,3,3,5} On sorting the second array elements in descending order the corresponding values in the first array has to be interchanged. First array={31,55,74,88,12} Second array={5,5,3,3,2}
Upvotes: 0
Views: 910
Reputation: 737
You can simply write two for loops to sort the second array, and make the same changes to the first array at the same time.
for (int i = 0; i < array2.length; i++){
for (int j = 0; j < array2.length; j++){
if (array2[i] < array2[j] && i < j){
int temp1 = array1[i];
int temp2 = array2[i];
array1[i] = array1[j];
array2[i] = array2[j];
array1[j] = temp1;
array2[j] = temp2;
}
}
}
While the second array is being sorted, the first array's elements are being moved the exact same way, regardless of their values.
Hope this helps!
Upvotes: 1
Reputation: 8696
Sounds like you short be storing an array of objects, where each object has two values.
public class X implements Comparable<X> {
private int a;
private int b;
public X(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(X other) {
return a - other.a;
}
}
Then you can make a list of these items, and sort them.
List<X> items = ... // Fill in the blanks
Collections.sort(items);
Upvotes: 3