如果我把下面这几行代码放在下面这几行代码中,程序就会像我预期的那样工作:
temp = arr[x];
arr[x] = arr[y];
arr[y] = temp; 在selectionSort函数下,但不使用交换函数。
下面是我的代码:
class selectionSort {
public static void printArray(int[] arr) {
for (int x = 0; x < arr.length; x++) {
System.out.print("[" + arr[x] + "],");
}
System.out.println();
}
public static void selectionSort(int[] arr) {
for (int x = 0; x < arr.length - 1; x++) {
for (int y = x + 1; y < arr.length; y++) {
if (arr[x] > arr[y]) {
swap(arr[x], arr[y]); // this is the line that doesn't work
// int temp = arr[x];
// arr[x] = arr[y];
// arr[y] = temp;
}
}
}
System.out.println();
}
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
public static void main(String[] args) {
int[] arr = new int[] {
32,
213,
432,
21,
2,
5,
6
};
printArray(arr);
selectionSort(arr);
printArray(arr);
}
}有没有人能解释一下原因,或者给我一些提示?
谢谢!
发布于 2019-01-29 05:52:24
Java中的所有东西都是通过值传递的,包括对数组的引用。您需要将int[]数组传递给交换方法,以便交换方法可以正确地修改该数组,如下所示:
class selectionSort{
public static void printArray(int[] arr){
for(int x = 0; x < arr.length; x++){
System.out.print("[" + arr[x] + "],");
}
System.out.println();
}
public static void selectionSort(int[] arr){
for(int x =0; x < arr.length-1; x++){
for(int y = x + 1; y < arr.length; y++){
if(arr[x] > arr[y]){
swap(arr[x], arr[y], arr);
}
}
}
System.out.println();
}
public static void swap(int x, int y, int[] arr){
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public static void main(String[] args){
int[] arr = new int[]{32,213,432,21,2,5,6};
printArray(arr);
selectionSort(arr);
printArray(arr);
}
}看看这个重复的答案(第三个答案向下):Jave method to swap primitives
https://stackoverflow.com/questions/54410043
复制相似问题