首页 > 解决方案 > 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);
 }
}

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

谢谢!

标签: java

解决方案


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


推荐阅读