Java 为什么这个自定义sortarray函数无法对数组进行排序?
我一直在研究Java数组,并试图创建自己的SortArray函数,而不是使用其他人的。如果我通过数组 [1,2,3,4,5]在SortArray函数中,它应该返回另一个数组[5,4,3,2,1],将数组从高到低排序。相反,该函数返回与参数中的数组完全相同的数组。我评论了代码中每个代码块应该做什么,如果你发现了什么,请告诉我Java 为什么这个自定义sortarray函数无法对数组进行排序?,java,arrays,sorting,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 f
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;
}
你根本不是在变异数组。您也根本没有在数组中变异元素。你只是在追踪最高点是什么。然后,由于作用域消失,所以最高值消失。简单地说,您永远不会更新数组。您在哪里更改数组?您所要做的就是更改int highest和minIndex,这是for循环变量,所以您甚至不应该更改它