簡體   English   中英

使用 compareTo 按升序對一個數組進行排序

[英]Using compareTo to sort one array in ascending order

在沒有排序功能的情況下需要幫助排序

不能只用一個循環對數組進行排序。 如果不允許使用sort方法,則可以使用經典的冒泡排序:

for (int i = 0; i < ch.length; i++) {
     for (int j = 0; j < ch.length - 1; j++) {
         if (ch[j].compareTo(ch[j + 1]) < 0) {
             Chocolate temp = ch[j];
             ch[j] = ch[j + 1];
             ch[j + 1] = temp;
         }
     }
}

但是你需要 in for 來實現它。

只要您有以下約束,您就可以在不使用任何類型的常見排序技術的情況下進行排序:

  1. 用於排序的字段是整數或可以轉換為整數。
  2. 該字段的整數值范圍在一個小的預定義范圍內。

在您的情況下,您的示例滿足這兩個約束。

  1. 您正在按cQuantity字段排序, cQuantity字段是一個整數。
  2. cQuantity字段在 0 到 19 范圍內。

你可以做的是:

  1. 創建一個Chocolate[20][20]數組。 讓我們稱它為sorted
  2. 迭代ch並將每個Chocolate放入上面sorted數組中,使用它們的getQuantity字段作為索引。 如果我們有不止一種具有相同getQuantity Chocolate ,則將它們添加到相同的索引下。
  3. 迭代sorted並打印它的值,如果它不是null

這是代碼:

Chocolate[][] sorted = new Chocolate[20][20];        

    for (Chocolate c : ch) {
        Chocolate[] bucket = sorted[ c.getQuantity() ];
        if (bucket == null) {
            bucket = new Chocolate[20];
            bucket[0] = c;
            sorted[ c.getQuantity() ] = bucket;
        }else {
            //if we already have entry under this index, find next index that is not occupaed and add this one
            for (int i = 0; i < bucket.length; i++) {
                if (bucket[i] == null) {
                    bucket[i] = c;
                    break;
                }
            }
        }
    }

    for (Chocolate[] bucket : sorted) {
        if ( bucket != null) {
            //System.out.println("b");
            for (Chocolate c : bucket) {
                if (c != null) System.out.println( c.getName() + " " + c.getQuantity() );                    
            }   
        }      
    }

暫無
暫無

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

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