3 回答

TA贡献1799条经验 获得超8个赞
Java 中的所有内容都是按值传递的,包括对数组的引用。您需要将 int[] 数组传递给 swap 方法,以便 swap 方法可以正确修改数组,如下所示:
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);
}
}

TA贡献1777条经验 获得超3个赞
当您在选择 sort() 中调用 swap(arr[x],arr[y]) 时,它将不起作用,因为您是按值而不是按引用调用函数。因此,在 swap(int x, int y) 内部,值正在交换,但并未反映在数组中。当您将行放在选择 sort() 中时,它将起作用,因为 arr[x] 和 arr[y] 仅在范围内。
添加回答
举报