简体   繁体   English

使用方法的冒泡排序数组

[英]Bubble sort array using methods

I'm writing code that takes the input for the array length and the items on the array, it then uses a bubble sorting method to put the items of the array in order.我正在编写代码,输入数组长度和数组上的项目,然后使用冒泡排序方法将数组中的项目按顺序排列。

This is the desired input output这是所需的输入 output

Enter the number of items in array:
5

Enter the items:
5
6
4
2
3

The sorted array is:
2
3
4
5
6

The problem I'm having is the method does not seem to be reading the user's inputs.我遇到的问题是该方法似乎没有读取用户的输入。

This is the code I have这是我的代码

import java.util.Scanner;

public class Main {
    private static int[] array;
    public static void main(String[] args) {
        int arrayLength;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of items in array: ");
        arrayLength = scanner.nextInt();
        int[] array = new int[10];
        System.out.println("Enter the items: ");
        for (int i = 0; i < arrayLength; i++) {
            array[i] = scanner.nextInt();
        }
        bubbleSort();
    }

    public static void bubbleSort() {
        int i, j, temp;
        boolean swap;
        for (i = 0; i < array.length - 1; i++) {
            swap = false;
            for (j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swap = true;
                }
            }
            if (swap == false)
                break;
        }
        System.out.print("The sorted array is: ");
        for (i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
            System.out.println();
        }
    }
}

Break the problem down into smaller problems.把问题分解成更小的问题。 Each of these small problems will become a method.这些小问题中的每一个都会成为一种方法。 A method has inputs (arguments) and an output (a return value).方法具有输入(参数)和 output(返回值)。 One way to look at what you're trying to do is:查看您正在尝试做的事情的一种方法是:

  1. Read in an array读入一个数组
  2. Sort the array对数组进行排序
  3. Print the sorted array打印排序后的数组

The first method will return an int[] given an InputStream :第一个方法将返回一个int[]给定InputStream

static int[] readArray(InputStream in) {
    System.out.print("Enter the number of items in array: ");
    Scanner scanner = new Scanner(in);
    int arrayLength = scanner.nextInt();
    int[] array = new int[arrayLength]; // there was a problem here, in your code the array had a fixed length of 10

    System.out.println("Enter the items: ");
    for (int i = 0; i < arrayLength; i++) {
        array[i] = scanner.nextInt();
    }
    return array;
}

The second method will return an int[] sorted with the bubble sort algorithm, given an int[] argument.给定一个int[]参数,第二种方法将返回一个使用冒泡排序算法排序的int[] []。

static int[] bubbleSort(int[] array) {
    int i, j, temp;
    boolean swap;
    for (i = 0; i < array.length - 1; i++) {
        swap = false;
        for (j = 0; j < array.length - i - 1; j++) {
            if (array[j] > array[j + 1]) {
                temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
                swap = true;
            }
        }
        if (!swap) {
            break;
        }
    }
    return array;
}

The third will print it out, returning nothing ( void ).第三个将打印出来,不返回任何内容( void )。

static void print(int[] array) {
    for (int i = 0; i < array.length; i++){
        System.out.println(array[i]);
    }
}

Put the pieces together and you have把碎片放在一起,你就有了

public static void main(String[] args) {
    // get input from user
    int[] array = readArray(System.in);
    // sort it
    int[] sorted = bubbleSort(array);
    // print sorted array
    System.out.println("The sorted array is: ");
    print(sorted);
}

As noted in the comment in the readArray(InputStream) method, there was a problem in your original code since the array's length was fixed (10).readArray(InputStream)方法中的注释中所述,由于数组的长度是固定的(10),因此您的原始代码存在问题。 These kinds of problems are easier to spot when using concise methods that do just one thing.当使用只做一件事的简洁方法时,这些问题更容易被发现。 By breaking the code down into smaller pieces it's also easier to test it.通过将代码分解成更小的部分,也更容易对其进行测试。

  1. Please be consistent with your use of spaces around names and symbols.请与您在名称和符号周围使用空格保持一致。 It will make your code look as though it was written by someone who cares, rather than someone who just head-butted the keyboard strategically.它将使您的代码看起来好像是由关心的人编写的,而不是只是战略性地敲击键盘的人。 This will instinctively make people think better of you and your work, always a good thing to aim for:)这会本能地让人们对你和你的工作有更好的看法,这总是一件好事:)

  2. int[] array = new int[10]; is problematic.是有问题的。 Where did that 10 come from?10是哪里来的? Never, ever use magic numbers in your code.永远不要在代码中使用幻数。 Even something like 12, to represent the number of months in a year, is technically a variable which could change one day.即使是像 12 这样表示一年中的月数的数字,从技术上讲也是一个变量,可能会在一天内改变。 Assign the number to a named variable, and use the name instead.将数字分配给命名变量,并改用名称。 I would have hinted that here lies the source of your dilemma, but saka1029 got there first.我会暗示这就是你困境的根源,但 saka1029 先到了那里。

  3. You declare a variable called array at the start of your class, but then define a duplicate in the main() method.您在 class 的开头声明了一个名为数组的变量,然后在 main() 方法中定义了一个副本。 User inputs are being added to the array in main(), but bubbleSort() is using the class variable which never gets anything added to it.用户输入被添加到 main() 中的数组中,但 bubbleSort() 使用的是 class 变量,该变量永远不会添加任何内容。 Option 1: declare the array as a class variable and use it in each method.选项 1:将数组声明为 class 变量并在每个方法中使用它。 Option 2: declare it in main(), then pass it as a parameter when you invoke the sorting method, ie bubbleSort(array) .方案2:在main()中声明,然后在调用排序方法时作为参数传递,即bubbleSort(array) I would prefer the latter, as you are being much clearer about what bubbleSort is sorting.我更喜欢后者,因为您对 bubbleSort 排序的内容更加清楚。

  4. Your methods do too much, and have different levels of abstraction, which is a pretty common feature for new programmers so don't feel bad about it.你的方法做的太多了,并且有不同的抽象级别,这对于新程序员来说是一个很常见的特性,所以不要为此感到难过。 However, do improve it, main() has both fiddly details to get the information.但是,一定要改进它,main() 具有获取信息的繁琐细节。 and a method call in which the work to sort the array is handled elsewhere.以及一个方法调用,其中对数组进行排序的工作在其他地方处理。 That's an ugly and confusing mix, Abstract the data collection, just as you already did for the sorting.这是一个丑陋且令人困惑的组合,抽象数据集合,就像您已经为排序所做的那样。 to make things more balanced, Ideally.理想情况下,使事情更加平衡。 your main() should read like an index of activities which are all handled in other methods, As for methods doing too much, your bubbleSort() sorts an array (good).您的 main() 应该读起来像所有在其他方法中处理的活动的索引,至于方法做得太多,您的 bubbleSort() 对数组进行排序(好)。 but also and very unexpected prints it (bad).但也非常意外地打印它(坏)。 The method name does not indicate that the array gets printed.方法名称并不表示数组被打印。 Let's try我们试试看

public static void main(String[] args) {
    int[] array = getArray();
    bubbleSort(array);
    printArray(array);
}

Fix the errors which have crept in through points 2 and 3. Then, you don't have to change the logic of your code, just break it up into more logical methods:) Once you start routinely testing your code, this will be an incredibly important approach.修复通过第 2 点和第 3 点潜入的错误。然后,您不必更改代码的逻辑,只需将其分解为更合乎逻辑的方法即可:) 一旦您开始定期测试您的代码,这将是一个非常重要的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM