gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:42:45 25 4
gpt4 key购买 nike

我有原始数组

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

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

最佳答案

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

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

关于java - 如何在不破坏原始数组的情况下对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16108860/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com