2017-10-09 33 views
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; 
} 
+0

简而言之,你永远不会更新数组。 – Robert

+0

你从哪里改变阵列?你所要做的就是改变int的'highest'和'minIndex'这是for循环变量,所以你甚至不应该改变它 – Tyler

回答

1

你根本没有变异array。你根本不会在array中突变元素。你只是追踪最高的是什么。然后highest消失,因为范围消失了。

相关问题