0

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}

1
  • 2
    Why not use a HashMap? You can keep elements of first array as keys and second array's values as its values. Sorting one will maintain the associativity of the second Commented Feb 11, 2016 at 18:32

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.