Skip to content
Advertisement

Get the indices of an array after sorting?

Suppose the user enter an array, for example:

JavaScript

which I did know the length of it

the index array would be:

JavaScript

Now, after sorting it using Arrays.sort(Array);

newArray will be like:

JavaScript

and the newIndex will be:

JavaScript

The problem is: how can I find the newIndex from the input Array?

Advertisement

Answer

Don’t sort the array to start with. Sort the index array, passing in a comparator which compares values by using them as indexes into the array. So you end up with newIndex as the result of the sort, and it’s trivial to go from there to the sorted array of actual items.

Admittedly that means sorting an array of integers in a custom way – which either means using an Integer[] and the standard Java library, or a 3rd party library which has an “IntComparator” interface which can be used in conjunction with a sort(int[], IntComparator) type of method.

EDIT: Okay, here’s an example comparator. For the sake of simplicity I’ll assume you only want to sort an “original” array of strings… and I won’t bother with nullity testing.

JavaScript

You’d use it like this:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement