簡體   English   中英

以降序對數組進行排序?

[英]Sorting an array in descending order?

我已經看過比較器和算法,但是我對它們沒有太多的了解。 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];
   }

單行代碼(不適用於原語):

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

Arrays.sort(temps1, Collections.reverseOrder());

您如何排序任何東西,只是從一個數組復制到另一個數組。 這是使用選擇排序的排序代碼。 public int [] descsort(){for(int i = 0,imax)//如果有更大的元素,請跟蹤它int index = j;

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

       temps[index]=temp;

     }
        return temps;
   }

可以按以下方式對Integer數組進行降序排序:

比較器比較器=新的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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM