简体   繁体   中英

Using compareTo to sort one array in ascending order

在没有排序功能的情况下需要帮助排序

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:

  1. The field to be used for sorting is integer or can be converted to integer.
  2. The range of integer value of the field is within a small predefined range.

In your case your example satisfies both constraints.

  1. You are sorting by cQuantity field which is an integer.
  2. The cQuantity field is within 0 to 19 range.

What you can do is:

  1. Create an Chocolate[20][20] array. Lets call it sorted .
  2. Iterate over 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.
  3. Iterate over 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM