0
我一直在看Java數組,並試圖創建自己的SortArray()函數,而不是使用別人的。如果我將數組 [1,2,3,4,5]傳遞給SortArray()函數,它應該返回另一個數組[5,4,3,2,1],將數組從高到低排序。相反,該函數返回與參數中的數組完全相同的數組。我評論了每個代碼塊應該在代碼中做什麼,請讓我知道如果你發現任何東西!爲什麼這個自定義sortarray函數無法排序數組?
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;
}
簡而言之,你永遠不會更新數組。 – Robert
你從哪裏改變陣列?你所要做的就是改變int的'highest'和'minIndex'這是for循環變量,所以你甚至不應該改變它 – Tyler