gpt4 book ai didi

java - 按降序对数组进行排序?

转载 作者:行者123 更新时间:2023-11-29 10:02:10 25 4
gpt4 key购买 nike

我看过比较器和算法,但我不太了解它们。来自 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;
}

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

int[] temps1 = new int[]{45, 76, 12, 102, 107, 65, 43, 67, 81, 14};

我的输出结果是这样的:。

The temperatures in descending order is:  0 0 0 0 0 0 0 0 0 0

为什么????

最佳答案

条件i <= 0永远不会遇见。

此外,tempArray[i] = temps[i];只会复制数组原样

要么:

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

或简单地

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

关于java - 按降序对数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21343138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com