9

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?

1
  • 1
    But if shows the same after sorting is not sorting at all... Commented Apr 19, 2013 at 16:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

IF so, How can i pass that sorted array to another method?
@userpane are you kidding? you can just call something like yourMethod(backup);
No no... I know that but It is in non-main method so I could not pass it to another non-main method.
you can return it. example: public int[] yourMethod() { //some other code return backup; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.