Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array without destroying the original array?

I have original array of

public static void main (String[] arg) {
  int[] array = {1,5,6,8,4,2}

  for (int i = 0; i < array.length; i++) {
    System.out.print("List 1 = " + array[i] + ",");
  }
  swap(array);
  for (int i = 0; i < array.length; i++) {
    System.out.print("List 2 = "+array[i] + ",");
  }
}
private static int swap (int[] list){
   Arrays.sort(list);
}

The output is

 List 1 = 1,5,6,8,4,2
 List 2 = 1,2,4,5,6,8

What I want the answer to be is

List 1 = 1,5,6,8,4,2
List 2 = 1,5,6,8,4,2

even after sorting. How can I do it?

like image 288
userpane Avatar asked Apr 19 '13 16:04

userpane


1 Answers

int[] originalArray = {1,5,6,8,4,2};
int[] backup = Arrays.copyOf(originalArray,originalArray.length);
Arrays.sort(backup);

After the execution of the code above, backup becomes sorted and originalArray stays same.

like image 146
Juvanis Avatar answered Sep 28 '22 04:09

Juvanis