为了账号安全,请及时绑定邮箱和手机立即绑定

selectionSort 程序中的交换功能问题

selectionSort 程序中的交换功能问题

肥皂起泡泡 2022-05-25 17:21:47
如果我输入这些代码行,该程序将按我的预期工作: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 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

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



查看完整回答
反对 回复 2022-05-25
?
守着星空守着你

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

    }

}


查看完整回答
反对 回复 2022-05-25
?
慕森王

TA贡献1777条经验 获得超3个赞

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



查看完整回答
反对 回复 2022-05-25
  • 3 回答
  • 0 关注
  • 113 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号