1

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?

3 Answers3

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
  • 17,266
  • 13
  • 70
  • 106
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:

  1. copy the array before sorting

    int[] unsorted = {2,3,1};
    int[] sorted = unsorted.clone();
    Arrays.sort(sorted);
    //find mean in sorted then proceed with unsorted
    
  2. create a custom sort function that retains a mapping between the positions.

  3. find the mean without sorting

leonardkraemer
  • 5,372
  • 1
  • 21
  • 44