猿问

selectionSort 程序中的交换功能问题

如果我输入这些代码行,该程序将按我的预期工作:


temp = arr[x];

arr[x] = arr[y];

arr[y] = temp; 

下selectionSort功能,但不带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]); // 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);

 }

}

谁能解释为什么,或者给我一些提示?


肥皂起泡泡
浏览 114回答 3
3回答

跃然一笑

Java 不发送变量引用。它会复制该值,这就是为什么原始值不会更改的原因。因此,您需要从交换函数返回交换后的值。

守着星空守着你

Java 中的所有内容都是按值传递的,包括对数组的引用。您需要将 int[] 数组传递给 swap 方法,以便 swap 方法可以正确修改数组,如下所示:class selectionSort{&nbsp; &nbsp; public static void printArray(int[] arr){&nbsp; &nbsp; &nbsp; &nbsp; for(int x = 0; x < arr.length; x++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;System.out.print("[" + arr[x] + "],");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }&nbsp; &nbsp; public static void selectionSort(int[] arr){&nbsp; &nbsp; &nbsp; &nbsp; for(int x =0; x < arr.length-1; x++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(int y = x + 1; y < arr.length; y++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(arr[x] > arr[y]){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; swap(arr[x], arr[y], arr);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }&nbsp; &nbsp; public static void swap(int x, int y, int[] arr){&nbsp; &nbsp; &nbsp; &nbsp; int temp = arr[x];&nbsp; &nbsp; &nbsp; &nbsp; arr[x] = arr[y];&nbsp; &nbsp; &nbsp; &nbsp; arr[y] = temp;&nbsp; &nbsp; }&nbsp; &nbsp; public static void main(String[] args){&nbsp; &nbsp; &nbsp; &nbsp; int[] arr = new int[]{32,213,432,21,2,5,6};&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; printArray(arr);&nbsp; &nbsp; &nbsp; &nbsp; selectionSort(arr);&nbsp; &nbsp; &nbsp; &nbsp; printArray(arr);&nbsp; &nbsp; }}

慕森王

当您在选择 sort() 中调用 swap(arr[x],arr[y]) 时,它将不起作用,因为您是按值而不是按引用调用函数。因此,在 swap(int x, int y) 内部,值正在交换,但并未反映在数组中。当您将行放在选择 sort() 中时,它将起作用,因为 arr[x] 和 arr[y] 仅在范围内。
随时随地看视频慕课网APP

相关分类

Java
我要回答