数组作为形参传递,经过排序后,为什么原有的数组没有被影响?

2025-03-07 08:17:06
推荐回答(1个)
回答1:

运行结果正常    不知道您说的原数组没有被影响指的是哪一行代码的数组    请标示

MaoPaoSort.java

package cn.itcast;

public class MaoPaoSort {
public static void sortArr(int[] arr) {
for (int x = 0; x < arr.length; x++) {
for (int y = 0; y < arr.length - 1 - x; y++) {
if (arr[y] > arr[y + 1]) {
swap(arr, y, y + 1);
}
}
}
}

public static void swap(int[] arr, int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}

TestSort.java

package cn.itcast;

public class TestSort {

public static void main(String[] args) {
int[] arr = { 23, 16, 34, 10, 66, 43, 78, 56 };
MaoPaoSort.sortArr(arr);
PrintArr(arr);
}

public static void PrintArr(int[] arr) {
StringBuffer sb = new StringBuffer("[");
for (int x = 0; x < arr.length; x++) {
if (x == arr.length - 1) {
sb.append(arr[x]).append("]");
} else {
sb.append(arr[x]).append(", ");
}
}
System.out.println(sb.toString());
}
}