[英]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 来实现它。
只要您有以下约束,您就可以在不使用任何类型的常见排序技术的情况下进行排序:
在您的情况下,您的示例满足这两个约束。
cQuantity
字段排序, cQuantity
字段是一个整数。cQuantity
字段在 0 到 19 范围内。你可以做的是:
Chocolate[20][20]
数组。 让我们称它为sorted
。ch
并将每个Chocolate
放入上面sorted
数组中,使用它们的getQuantity
字段作为索引。 如果我们有不止一种具有相同getQuantity
Chocolate
,则将它们添加到相同的索引下。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.