【问题标题】:Java recursion program not sorting the array [closed]Java递归程序未对数组进行排序[关闭]
【发布时间】:2020-10-27 18:28:13
【问题描述】:
public class bubbleSort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arr = {50,40,30,20,10};
        bubbleSort1(arr,0,arr.length-1);
        display(arr);
    }

    public static void bubbleSort1(int[] arr,int i, int li) {
        if (i==0) {
            return;
        }
        if (i==li) {
            bubbleSort1(arr,0,li-1);
            return;
        }
        if (arr[i]>arr(i+1)) {
            int temp = arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=temp;
        }
        bubbleSort1(arr,i+1,li);
    }

    public static void display(int[] arr) {
        for(int i=0;i<arr.length;i++) {
            System.out.print(arr[i]+" ");
        }
    }
}

我正在做冒泡排序,但代码不起作用,但我不知道为什么它只打印我提供给它的数组。

【问题讨论】:

  • 您正在为i 调用值为0 的方法,并且该方法的第一行是if(i==0) { return; }。那么,您的方法完全什么都不做,真的很令人惊讶吗?

标签: java recursion bubble-sort


【解决方案1】:

i == 0 时,您的方法bubbleSort1(...) 的第一行是return;。你是 main 方法调用该方法:bubbleSort1(arr,0,arr.length-1); ... i == 0 - 所以你的方法没有排序任何东西。

它应该看起来更像:

import java.util.Arrays;

public class BubbleSort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] list = { 50,40,30,20,10 };
        bubbleSort1(list,list.length);
        System.out.println(Arrays.toString(list));
    }
    public static void bubbleSort1(int[] list, int listLength) {
        if (listLength==1) { return; }
        for (int i=0; i<listLength-1; i++) {
            if(list[i] > list[i+1]) {
                int temp = list[i];
                list[i] = list[i + 1];
                list[i + 1] = temp;
            }
            bubbleSort1(list, listLength-1);
        }
    }
}

输出

[10, 20, 30, 40, 50]

为了清楚起见,我冒昧地重命名变量并删除了显示方法,因为Arrays.toString(list) 方法免费提供此功能:)

【讨论】:

    猜你喜欢
    • 2015-12-24
    • 1970-01-01
    • 2022-08-18
    • 2021-06-22
    • 1970-01-01
    • 2015-12-30
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多