在没有排序功能的情况下需要帮助排序
You cannot sort an array with only one loop. If you are not allowed to used sort
method you can do it with a classic bubble 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;
}
}
}
But you will need for in for to achieve it.
You can do sorting without using any type of common sorting technique as long as you have these constraints:
In your case your example satisfies both constraints.
cQuantity
field which is an integer.cQuantity
field is within 0 to 19 range. What you can do is:
Chocolate[20][20]
array. Lets call it sorted
.ch
and put each Chocolate
into the above sorted
array using their getQuantity
field as index. In case we have more than one Chocolate
with the same getQuantity
add them together under the same index.sorted
and print its value if it is not null
.Here is the code:
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() );
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.