如何在不破坏原始数组的情况下对数组进行排序?

时间:2013-04-19 16:04:12

标签: java arrays sorting

我有

的原始数组
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);
}

输出

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

我想要的答案是

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

即使在排序后。我该怎么办?

1 个答案:

答案 0 :(得分:18)

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

执行上述代码后,backup将排序,originalArray保持不变。