【问题标题】:Coding Bubble Sort using Java使用 Java 编码冒泡排序
【发布时间】:2017-05-01 06:05:35
【问题描述】:

我不知道我的编码是否正确,但有人可以确认我的 doBubbleSort 方法及其在 main 方法中的实现是否正确编程?我的编码要求我创建一个大小为 20 的数组,并用 1 到 1000 之间的随机整数填充它,而无需对其进行硬编码。结果应该显示原始的、未排序的整数列表;然后在单独的行上显示冒泡排序算法的每一次通过。我必须重复该程序,直到用户选择退出。 **我已经进行了编辑以确保我使用的任何变量都是根据 ArrayLists 声明的。

我希望我的输出结果如下所示的示例(尽管当我尝试做 20 时它只显示 5 个整数):

未排序列表:68 3 298 290 1
通行证 1:3 68 290 1 298
通行证 2:3 68 1 290 298
通行证 3:3 1 68 290 298
传球4:1 3 68 290 298

// Used to capture keyboard input
import java.util.*;

// Our class called BubbleSort
public class BubbleSort {

    // Create doBubbleSort method 
    public static void doBubbleSort(ArrayList<Integer> arr) {
        boolean needNextPass = true;
        while (needNextPass) {
            // Array may be sorted and next pass not needed 
            needNextPass = false;
            // Swap list
            for (int i = 0; i < arr.size()-1; i++) {
                if (arr.get(i) > arr.get(i+1)) {
                    int temp = arr.get(i);
                    arr.set(i, arr.get(i+1));
                    arr.set(i+1, temp);
                    printOut(i+1, arr); // using printOut method
                    needNextPass = true; // Next pass still needed
                }
            }
        }
    }

    private static void printOut(int pass, ArrayList<Integer> list) {
        System.out.print("PASS " + pass + ": ");
        for (int i = 0; i < list.size()-1; i++) {
            System.out.print(list.get(i) + ", ");
        }
        // Shows very last integer with a period
        System.out.print(list.get(list.size()-1) + "."); 
        System.out.println();
    }

    // Main method
    public static void main(String[] args) {
        ArrayList<Integer> array = new ArrayList<Integer>(); // Declare and instantiate a new ArrayList object
        Scanner userChoice = new Scanner(System.in); // User input for quitting program
        String choice = ""; // Will hold user choice to quit program
        boolean inputFlag = false; // True if input is valid, false otherwise

        // Repeat program until user chooses to quit
        while (inputFlag = true) {
            System.out.print("\nWould you like to continue the program? (Y/N): ");
            choice = userChoice.nextLine();
            if (choice.equalsIgnoreCase("Y")) {
                try {
                    /* Create an array of size 20 and populate it with random integers between 1 and 1000.
                    Do not ask user for the numbers and do not hard code them */
                    for (int i = 0; i < 20; i++) {
                        int integer = (int)(1000.0 * Math.random());
                        array.add(integer);
                    }
                    System.out.print("\nUNSORTED LIST: ");

                    //Display the 20 size of the unsorted ArrayList 
                    for (int i = 0; i < array.size() - 1; i++) {
                        System.out.print(array.get(i) + ", ");
                    }
                    // Shows very last integer with a period
                    System.out.print(array.get(array.size() - 1) + "."); 
                    System.out.println();
                    doBubbleSort(array);
                }

                catch (IndexOutOfBoundsException e) {
                    System.out.println("\nThere is an out of bounds error in the ArrayList.");
                }
            }
            else if (choice.equalsIgnoreCase("N")) {
                break;
            }
            // Error message when inputting anything other than Y/N
            else { 
                System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
                System.out.println("Please try again.");
            }
        }
    }
} 

【问题讨论】:

标签: java sorting bubble-sort


【解决方案1】:

随着您的实施,由于您似乎刚开始学习这一点,因此您应该改变一些事情。首先,由于 doBubbleSort 方法使用的是 int 数组,所以在 main 方法中也要使用 int 数组。

冒泡排序的实现也需要改变。您应该首先仔细研究其逻辑。不需要每次都遍历整个数组。

// Create doBubbleSort method 
public static void doBubbleSort(int[] arr) {
    boolean needNextPass = true;
    // Array may be sorted and next pass not needed 
    // Swap list
    for (int i = 0; i < arr.length - 1; i++) {
        if (needNextPass) {
            needNextPass = false;
            for (int j = arr.length - 1; j > i; j--) {
                int temp;
                if (arr[j] < arr[j - 1]) {
                    temp = arr[j - 1];
                    arr[j - 1] = arr[j];
                    arr[j] = temp;
                    needNextPass = true; // Next pass still needed
                }
            }
            printOut(i + 1, arr); // using printOut method
        }
    }
}

然后,打印数组。

private static void printOut(int pass, int[] list) {
    System.out.print("PASS " + pass + ": ");
    for (int i = 0; i < list.length - 1; i++) {
        System.out.print(list[i] + ", ");
    }
    // Shows very last integer with a period
    System.out.print(list[list.length - 1] + ".");
    System.out.println();
}

现在主要方法。我已经更改了重新运行程序的输入处理部分,并使用了您最初发布的 int 数组。

// Main method
public static void main(String[] args) {
    int[] array = new int[20]; // Declare and instantiate a new ArrayList object
    Scanner userChoice = new Scanner(System.in); // User input for quitting program
    boolean inputFlag = true; // True if input is valid, false otherwise
    String choice;

    // Repeat program until user chooses to quit
    while (inputFlag == true) {

        try {
            /* Create an array of size 20 and populate it with random integers between 1 and 1000.
             Do not ask user for the numbers and do not hard code them */
            for (int i = 0; i < 20; i++) {
                int integer = (int) (1000.0 * Math.random());
                array[i] = integer;
            }
            System.out.print("\nUNSORTED LIST: ");

            //Display the 20 size of the unsorted ArrayList 
            for (int i = 0; i < array.length - 1; i++) {
                System.out.print(array[i] + ", ");
            }
            // Shows very last integer with a period
            System.out.print(array[array.length - 1] + ".");
            System.out.println();
            doBubbleSort(array);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("\nThere is an out of bounds error in the ArrayList.");
        }

        System.out.print("\nWould you like to continue the program? (Y/N): ");
        choice = userChoice.nextLine();

        while (!(choice.equalsIgnoreCase("Y")) && !(choice.equalsIgnoreCase("N"))) {
            // Error message when inputting anything other than Y/N
            System.out.println("\nERROR. Only Y, y, N, or n may be inputted.");
            System.out.println("Please try again.");
            choice = userChoice.nextLine();
        }

        if (choice.equalsIgnoreCase("N")) {
            inputFlag = false;
        }

    }
}

}

【讨论】:

  • 感谢您的帮助!是的,我对编码还是很陌生。哎呀,我认为如果我把 int[] array = new int[20];这就是为什么我选择使用 ArrayList...再次感谢,总是从这个网站学到很多东西。
  • 这是硬编码,是的!我之所以这么说,是因为您特别说过您需要 20 个元素。您可以让用户输入数组大小的值,然后使用它来初始化数组。 int arraySize = scanner.nextInt(); 然后,int[] array = new int[arraySize]; 很高兴它有帮助。编码愉快!
【解决方案2】:

您为冒泡排序编写了太多样板代码。对于冒泡排序,使用递归方法。我给你写了简单的冒泡方法,输出做你想做的事

private int[] bubbleSort(int[] arr){

    int c;
    boolean isArranged = false;

    for (int i = 0; i < arr.length; i++) {
        if (i < (arr.length - 1) && arr[i] > arr[i+1]){
            c = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = c;
            isArranged = true;
        }
    }

    if (isArranged){
        return bubbleSort(arr);
    }else{
        return arr;
    }
}

这样称呼:

Scanner in = new Scanner(System.in);
    int length = in.nextInt();
    int[] arr = new int[length];

    for (int i = 0; i < length; i++) {
        arr[i] = in.nextInt();
    }

    Main main = new Main();

    int[] newArr = main.bubbleSort(arr);

    for (int i = 0; i < newArr.length; i++) {
        System.out.print(newArr[i] + " ");
    }

你可以用 ArrayList 代替 int 数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 2014-06-25
    • 2017-06-17
    • 2012-12-09
    • 2019-10-04
    • 2013-09-04
    • 1970-01-01
    • 2018-08-19
    相关资源
    最近更新 更多