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

标签 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;
    }         

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

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/

相关文章:

loops - 如何在 Ansible 中获取子组列表?

java - 在 Spring 表单中使用 AJAX 调用

javascript - 过滤对象数组以仅具有具有相同特定属性的该对象的最后一次出现

php数组加载到javascript

java - Android:如何在更新 UI 的同时创建循环延迟

java - 如何在 Java 中循环播放音频?

java - libjvm.so : to link or not to link?

java - 使用 Jersey 1.x 自定义注解注入(inject)

java - Android 编程时 Eclipse 出现空指针异常

c - 如何使用字符串创建一个整数数组进行索引