【问题标题】:Sorting an array in descending order?按降序对数组进行排序?
【发布时间】:2014-02-16 01:33:32
【问题描述】:

我看过比较器和算法,但我无法理解它们。来自 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

为什么????

【问题讨论】:

  • 这里可以看到Comparator接口的使用方法:stackoverflow.com/questions/7414299/…
  • @HovercraftFullOfEels 我做了一个方法,它事先对数组进行排序,所以这不是问题。

标签: java arrays loops assign


【解决方案1】:

条件i &lt;= 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];
   }

【讨论】:

  • 我的数组越界异常
  • tempArray[temps.length-i] 到 tempArray[temps.length-1-i]
【解决方案2】:

你如何排序任何东西,你只是从一个数组复制到另一个数组。这是使用选择排序的排序代码。 公共 int [] descsort(){ for(int i=0,imax)//如果有更大的元素,跟踪它 int 索引=j;

       int temp=temps[max];
       temps[max]=temps[index];

       temps[index]=temp;

     }
        return temps;
   }

【讨论】:

    【解决方案3】:

    单线(不适用于原语):

    Integer[] temps1 = new Integer[] { 45, 76, 12, 102, 107, 65, 43, 67, 81, 14 };
    
    Arrays.sort(temps1, Collections.reverseOrder());
    

    【讨论】:

      【解决方案4】:

      可以这样对整数数组进行降序排序:

      Comparator 比较器 = new Comparator() {

              @Override
              public int compare(Integer o1, Integer o2) {
                  return o2.compareTo(o1);
              }
          };
          Integer[] array = new Integer[] { 9,1, 0, 7, 0, 0, 0, 5, 0 };
          Arrays.sort(array, comparator);
          System.out.println(Arrays.toString(array));
      

      【讨论】:

        猜你喜欢
        • 2013-09-20
        • 1970-01-01
        • 1970-01-01
        • 2011-02-09
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        • 2015-08-30
        • 2021-11-19
        相关资源
        最近更新 更多