java - 为什么这个自定义 sortarray 函数无法对数组进行排序?

标签 java arrays sorting

我一直在研究 Java 数组,并尝试创建自己的 SortArray() 函数,而不是使用其他人的。如果我传递数组 [1, 2, 3, 4, 5] 到 SortArray() 函数中,它应该返回另一个数组 [5, 4, 3, 2, 1],将数组从高到低排序。相反,该函数返回与参数中的数组完全相同的数组。我在代码中注释了每个代码块应该做什么,如果您发现任何问题请告诉我!

public static int[] sortArray(int[] array) {
    //Declare the highest value found so far
    int highest;

    //loop through every index in the array
    for (int minIndex = 0; minIndex < array.length; minIndex++) {

        //Set the current highest value to the first index
        highest = array[minIndex];

        //loop through every index past the minimum to check if there is a higher numer
        //do not check the indexes before the minIndex
        for (int i = 0 + minIndex; i < array.length; i++) {
            //Check to see if the current index is higher than the highest
            //if so, make that value the new highest and loop again from the next index
            if (array[i] > highest) {
                highest = array[i];
                minIndex ++;
            }
        }
    }
    return array;
}

最佳答案

你根本没有改变array。您也根本不会改变 array 中的元素。你只是追踪最高的值。然后 highest 消失,因为范围消失了。

关于java - 为什么这个自定义 sortarray 函数无法对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46653036/

相关文章:

java - 以可靠的方式归档的 JMS 消息

java - 从 jaxb 生成正确的 xml

c - 如何在运行时分配多维数组?

c++ - 循环数组(队列)迭代器

Python 字符串的数值排序

arrays - 对作为哈希值的数组进行排序

java - 如何创建 ServletContext 的模拟属性?

java - 无法启动 cygpath

c++ - 检查 C++ 数组是否为 Null

c# - 我如何按字母顺序对我的 ListView 进行排序?