I had to sort array to find its Median, but now I need to recover the initial value of array, put it as it was. Is that possible?
Asked
Active
Viewed 215 times
1
-
3How about copy array before sort and after sort you can use your copy? – jker Nov 27 '18 at 22:16
-
2This. Any strategy for saving the original order and then sorting back to it would dwarf the time copying the array. – Duane Nov 27 '18 at 22:19
-
@MartynasKrupskis Please mark one of the answers as accepted. – MC Emperor Nov 12 '20 at 16:45
3 Answers
6
You can't do that. Sorting is irreversible. However, you could also add all elements of your original list to a new ArrayList and then sort that list.
List<String> original = ...;
List<String> copy = new ArrayList<>(original);
Collections.sort(copy);
I would not worry about the footprint of the copy. It is a shallow copy, that means that the elements themselves are not copied, but only a new list is created with references to the elements contained in the original list. And that operation is quite fast. I would only worry if the list was very, very big.

MC Emperor
- 22,334
- 15
- 80
- 130
-
in this case what is the recommendation if the list was very very big? – experiment unit 1998X Apr 25 '23 at 05:30
-
1@experimentunit1998X Well, either not sort it, or, if the sorting is really really important for you, then I would use something like a `TreeSet` or a similar structure. – MC Emperor Apr 25 '23 at 07:38
3
Using @McEmperors answer but with arrays
Object[] saved = Arrays.copyOf(old, old.length);
Array.sort(old);

Duane
- 281
- 1
- 5
1
There are several ways to achieve what you want:
-
int[] unsorted = {2,3,1}; int[] sorted = unsorted.clone(); Arrays.sort(sorted); //find mean in sorted then proceed with unsorted
create a custom sort function that retains a mapping between the positions.

leonardkraemer
- 6,573
- 1
- 31
- 54