I have an array of doubles, in Java : arr1
which I want to sort. Most probably the first option would be the utility method Arrays.sort(double[])
.
The idea is that I want the same changes (e.g. value at index i
is interchanged with value at index j
in arr1
) to be reflected in another array of integers: arr2
(in the sense that the values at the same indexes are changed also in arr2
).
Is there a simple way (a trick) to accomplish this in Java? Or the only way is to implement the sorting algorithm by myself?
UPDATE: I see that people recommend replacing the two arrays with one array of objects containing the 2 values (one from arr1
and one from arr2
). Wouldn't this bring some efficiency penalties. In other words, isn't it less efficient to sort an array of objects than an array of primitive types (doubles in this case) ?
The data is completely static. It's large (it fits in memory) but static.
Rather than trying to maintain sorted parallel arrays, a cleaner solution would be to create a class that encapsulates both of your data values, and just have one array of objects.
(But to answer your question, there is no built-in way to do this in Java. Implementing your own sort routine that keeps two arrays sorted based on values in one of them would work for a small amount of data that isn't likely to change, but it would be difficult to maintain.)
One solution which is doesn't impact the performance of sorting, ie still O(nlog(n)) time complexity.
array[i] -> i
Edit: Raihan comment make me look miserable :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With