繁体   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