我一直在研究 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/