如何在不使用 Arrays.sort() 的情况下对整数数组从最小值到最大值进行排序?

How do I sort an array of integers from minimum to maximum value without using Arrays.sort()?

我正在学习如何使用数组,我正在尝试使用两个 ArrayList 手动对整数数组进行排序。

这是我目前拥有的:

public Object[] arraySort (int[] importedArray) {
        // !!! This method returns the original imported method (?). !!!
        ArrayList<Integer> unsorted = new ArrayList<>();
        ArrayList<Integer> sorted = new ArrayList<>();
        // Convert importedArray into unsorted Integer ArrayList
        for (int i = 0; i < importedArray.length; i++) {
            unsorted.add(importedArray[i]);
        }
        // Find minimum value of unsorted ArrayList, add to sorted ArrayList, and remove min value from unsorted
        for (int i = 0; i < unsorted.size(); i++) {
            int min = Integer.MAX_VALUE;
            int index = 0;
            for (int j = 0; j < unsorted.size(); j++) {
                if (unsorted.get(j) < min) {
                    min = unsorted.get(j);
                    index = j;
                }
            }
            unsorted.remove(index);
            sorted.add(min);
        }
        return unsorted.toArray();
    }

但是,当我 运行 该方法时,我得到了相同的导入数组。将 int[] 转换为 ArrayList 的第一个 for 循环在我使用 print 检查时显然有效,因此问题很可能出现在第二个 for 循环中。

我也尝试过其他的插入排序方式,但我不确定这种排序方式有什么问题。我在某个地方完全搞砸了吗?还是这种方法不可行?预先感谢您的帮助!

首先,您应该 return 排序数组而不是未排序数组。在循环头中使用 unsorted.size() 时也应该小心,因为程序将在每次迭代完成时调用该方法。但是由于您使用 update.remove(index) 减小了循环内部的大小,因此大小不会保持不变,您只是跳过了一些值。因此,您应该在开始循环之前将该值保存在变量中。以下代码对我有用:

public Object[] arraySort(int[] importedArray) {
    ArrayList<Integer> unsorted = new ArrayList<>();
    ArrayList<Integer> sorted = new ArrayList<>();
    for (int i = 0; i < importedArray.length; i++) {
        unsorted.add(importedArray[i]);
    }
    int size = unsorted.size();
    for (int i = 0; i < size; i++) {
        int min = Integer.MAX_VALUE;
        int index = 0;
        for (int j = 0; j < unsorted.size(); j++) {
            if (unsorted.get(j) < min) {
                min = unsorted.get(j);
                index = j;
            }
        }
        unsorted.remove(index);
        sorted.add(min);
    }
    return sorted.toArray();
}