按降序排列数组?

Pat*_*ens 1 java arrays loops assign

我看过比较器和算法,但我对它们没有多大意义.来自java.util.Collections的比较器.所以我选择使用这个:

//return an array in descending order, using set algorithm
    public int[] descendSort()
    {
       int[] tempArray = new int[temps.length];

       for (int i = temps.length-1; i <= 0; --i)  
       {
            tempArray[i] = temps[i];
       }

    return tempArray;
    }         
Run Code Online (Sandbox Code Playgroud)

我在客户端创建的数组是这样的:

int[] temps1 = new int[]{45, 76, 12, 102, 107, 65, 43, 67, 81, 14};
Run Code Online (Sandbox Code Playgroud)

我的输出结果如下:

The temperatures in descending order is:  0 0 0 0 0 0 0 0 0 0
Run Code Online (Sandbox Code Playgroud)

为什么????

zak*_*ter 8

这种情况i <= 0永远不会得到满足.

此外,tempArray[i] = temps[i];将只是按原样复制数组.

要么:

   for (int i = temps.length-1; i >= 0; --i)  
   {
        tempArray[temps.length-1-i] = temps[i];
   }
Run Code Online (Sandbox Code Playgroud)

或者干脆

   for (int i = 0; i < temps.length; ++i)  
   {
        tempArray[temps.length-1-i] = temps[i];
   }
Run Code Online (Sandbox Code Playgroud)

  • tempArray [temps.length-i]到tempArray [temps.length-1-i] (2认同)