Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array and reflect the changes in another array

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.

like image 738
Razvan Avatar asked Oct 10 '12 16:10

Razvan


2 Answers

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.)

like image 126
Bill the Lizard Avatar answered Sep 18 '22 15:09

Bill the Lizard


One solution which is doesn't impact the performance of sorting, ie still O(nlog(n)) time complexity.

  • Use a map to store array[i] -> i
  • Sort the array
  • Iterate over the sorted array, and for each value, use it as a key for the map to retrieve the original index.

Edit: Raihan comment make me look miserable :(

like image 43
UmNyobe Avatar answered Sep 21 '22 15:09

UmNyobe