Suppose the user enter an array, for example:
Array = {France, Spain, France, France, Italy, Spain, Spain, Italy}
which I did know the length of it
the index array would be:
index = {0, 1, 2, 3, 4, 5, 6, 7}
Now, after sorting it using Arrays.sort(Array);
newArray will be like:
newArray = {France, France, France, Italy, Italy, Spain, Spain, Spain}
and the newIndex will be:
newIndex = {0, 2, 3, 4, 7, 1, 5, 6}
The problem is: how can I find the newIndex from the input Array?
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
newIndexas 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 asort(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.
You’d use it like this: