0

I'm trying to do descended sort with Double values.

Double[] test = {7.0, 2.0, -5.0, 5.0, 9.0};
Arrays.sort(test, Collections.reverseOrder());
System.out.println(Arrays.toString(test)); // [9, 7, 5, 2, -5]

So far, it looks good. But I need to get the index for the sorting as well. How can I do that?

I know that the sorted index did go from 0 1 2 3 4 to 4 0 3 1 2.

How can I get that index?

2

3 Answers 3

2

Write a custom comparator that sorts a list of indices, while comparing the double values in the original list.

Then create a new array, iterate over all indices and map the double values to the right location based on the index.

Integer[] indexes = IntStream.range(0, test.length).boxed().toArray(Integer[]::new);

// indexes contains [0, 1, 2, 3, 4].

Arrays.sort(indexes, Comparator.<Integer>comparingDouble(i -> test[i]).reversed());

// indexes is now [4, 0, 3, 1, 2].

// Now you can copy back into test:
test = IntStream.range(0, test.length).mapToObj(i -> test[i]).toArray(Double[]::new);

Ideone Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Two remarks: is it possible to do this using the base type double and int for the arrays? It would also be nice to sort the array itself rather than creating a copy?
The demo is also missing that last line!
1

If the numbers in your array are distinct, you can use a Map to store the numbers as keys and their indices as values. Once the numbers are sorted, you can iterate the sorted array, retrieve the values from the Map by the number from each iteration and print them.

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Double[] test = { 7.0, 2.0, -5.0, 5.0, 9.0 };
        Map<Double, Integer> map = new HashMap<Double, Integer>();
        for (int i = 0; i < test.length; i++) {
            map.put(test[i], i);
        }
        Arrays.sort(test, Collections.reverseOrder());

        // Display indices
        for (Double n : test) {
            System.out.print(map.get(n) + " ");
        }
    }
}

Output:

4 0 3 1 2 

Comments

0

If you know your values are distinct (as in your example), an alternative is to use the List.indexOf() method which finds the index of a particular object.

Double[] test = {7.0, 2.0, -5.0, 5.0, 9.0};
List<Double> doubleList = new ArrayList<>(Arrays.asList(test));
Arrays.sort(test, Collections.reverseOrder());

// find the indices.           
int[] indices = Arrays.stream(test).mapToInt(ob->doubleList.indexOf(ob)).toArray();

System.out.println(Arrays.toString(indices));

prints

[4, 0, 3, 1, 2]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.