selectionSort程序中交换功能的问题

时间:2019-01-28 20:46:38

标签: java

如果我放置以下代码行,程序将按预期工作:

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);
 }
}

任何人都可以解释原因,或给我一些提示吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

当您在选择sort()中调用swap(arr [x],arr [y])时,它将无法工作,因为您是通过值而不是通过引用来调用函数。因此,在swap(int x,int y)内部,值正在交换,但未反映在数组中。将行放入选择sort()时,它将起作用,因为arr [x]和arr [y]仅在范围内。请通过以下链接进行更清晰的了解:

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/

答案 1 :(得分:0)

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);
    }
}

签出重复的答案(向下回答3):Jave method to swap primitives

答案 2 :(得分:0)

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