[英]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.