java - 使用 ArrayList 进行选择排序

标签 java arrays sorting arraylist selection

我正在尝试使用 ArrayList 编写选择排序。我的程序要求我创建一个大小为 20 的数组,并用 1 到 1000 之间的随机整数填充它(无需用户输入或硬代码)。输出将需要显示原始的未排序整数列表,并在单独的行上显示排序算法的每次传递。

我尝试创建一个选择排序方法,这就是我陷入困境的地方,因为我不确定如何将代码实现到我的主方法中。

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

未排序列表:3 68 298 290 1
通过1:1 68 298 290 3
通过2:1 3 298 290 68
通过 3: 1 3 68 290 298
通过 4:1 3 68 290 298

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

// Our class called SelectionSort
public class SelectionSort {

// Create doSelectionSort method 
public static int[] doSelectionSort(int[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        int pos = i;
        // find position of smallest num between (i + 1)th element and last element
        for (int j = i + 1; j <= arr.length; j++) {
            if (arr[j] < arr[pos])
                pos = j;

            // Swap min (smallest num) to current position on array
            int min = arr[pos];
            arr[pos] = arr[i];
            arr[i] = min;
        }
    }
    return arr;
}

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

            catch (IndexOutOfBoundsException e) {
                System.out.println("\nThere is an out of bounds error in the ArrayList.");
            }
            // Display each pass of the sorting algorithm on a separate line
            for (int i = 1; i < array.size(); i++) {
                System.out.print("PASS " + i + ": ");
                for (int arr2:array) {
                    System.out.print(arr2 + ", ");
                }
                System.out.print(array.get(array.size() - 1) + ".\n");
            }
        array.clear();
        }
        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.");
        }
    }
}
}

我也无法从每次传递中删除最后一个数字,因为它显示了两次..知道我应该做什么吗?

很抱歉我的编码很菜鸟,我仍在尝试理解它。

最佳答案

我修复了你的代码,它现在应该可以工作了。

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

// Our class called SelectionSort
public class SelectionSort {

    // Create doSelectionSort method 
    public static void doSelectionSort(ArrayList<Integer> arr) {
        for (int i = 0; i < arr.size(); i++) {
            // find position of smallest num between (i + 1)th element and last element
            int pos = i;
            for (int j = i; j < arr.size(); j++) {
                if (arr.get(j) < arr.get(pos))
                    pos = j;
            }
            // Swap min (smallest num) to current position on array
            int min = arr.get(pos);
            arr.set(pos, arr.get(i));
            arr.set(i, min);
            printOut(i + 1, arr);
        }
    }

    private static void printOut(int pass, ArrayList<Integer> array) {
        System.out.print("PASS " + pass + ": ");
        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();
    }

    // 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();
                    doSelectionSort(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 - 使用 ArrayList 进行选择排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41955427/

相关文章:

SQL 对每行中的列进行排序,并据此对行进行排序

python - 按值然后键对字典进行排序

java - 如何安装STS到eclipseoxy(2018.march) 市场上没有sts?

java - 如果在私有(private)构造函数中初始化,从静态方法访问时是否保证私有(private)静态字段为非空

php - HTTP post 数组与 PHP 合并

javascript - 在 JavaScript 中执行计算后,如何获取嵌套数组中的所有对象?

c++ - std::sort 和 std::stable_sort 在实践中的性能差距有多大?

Java CompareTo 方法未按预期工作

java - 为什么我不能直接在代码中使用 unicode 字符串文字

java - 尝试将新对象添加到数组时出现空指针异常?