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 74 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.
![](../../users/profiles/507738.webp)
MC Emperor
- 17,266
- 13
- 70
- 106
3
Using @McEmperors answer but with arrays
Object[] saved = Arrays.copyOf(old, old.length);
Array.sort(old);
![](../../users/profiles/282709.webp)
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.
![](../../users/profiles/4265739.webp)
leonardkraemer
- 5,372
- 1
- 21
- 44