如果我把下面这几行代码放在下面这几行代码中,程序就会像我预期的那样工作:
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:00:51
当你在selection sort()中调用swap(arrx,arry)时,它将无法工作,因为你是通过值而不是引用来调用函数的。因此,在swap(int,int )中,值是交换的,但不会反映在数组中。当您将行放入selection sort()中时,它将起作用,因为arrx和arry只在作用域内。为了更清楚起见,请浏览以下链接:
http://cs-fundamentals.com/tech-interview/c/difference-between-call-by-value-and-call-by-reference-in-c.php
https://javapapers.com/core-java/java-pass-by-value-and-pass-by-reference/
发布于 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
发布于 2019-01-29 07:53:26
Java不发送变量引用。它复制值,这就是原始值不变的原因。因此,您需要从交换函数返回交换的值。
https://stackoverflow.com/questions/54410043
复制相似问题