Java program to create a Descending Order using bucket sort

我与影子孤独终老i 提交于 2021-01-29 07:11:55

问题


I was making a program to take 10 user input values(1-100) and use bucket sort to sort it according to the user preference whether by ascending or descending order. I was able to create the ascending order. This is my code for ascending, but how could I make it descending?

 public class BucketSort{
    Scanner in = new Scanner(System.in);
 public  void bucketSort(int array[], int numBuckets){
  
  System.out.println("Choose Sorting Order:");
  System.out.println("[A] Ascending \n[D] Descending \n Enter choice: ");
  char choice2 = in.next().charAt(0);
    
  
    
  if (choice2 == 'A') {
    List<Integer>[] buckets = new List[numBuckets];
    System.out.println("The user inputted values are " + Arrays.toString(array));
    System.out.println("Algorithm choice is Bucket Sort");
    System.out.println("The sorting order choice is Ascending");
      // Creates empty buckets
for(int i =0; i < numBuckets; i++){
        
        buckets[i] = new LinkedList<>();
    
 }
for(int num: array){
     buckets[hash(num, numBuckets)].add(num);
  }
for(List<Integer> bucket :buckets) {
       Collections.sort(bucket);
 }
 int i = 0;
       for(List <Integer> bucket : buckets) {
           for (int num: bucket){
               array[i++] = num;
    }
}
 }
 private static int hash(int num, int numBuckets) {
   return num/numBuckets;
  }
 }

回答1:


Try the following:

Collections.sort(bucket, Collections.reverseOrder());

Keep in mind that you have to reverse the order of the buckets when you combine them into the array:

for(int index = buckets.length - 1; index >= 0; index--) {
    for (int num: buckets[index]){
       array[i++] = num;
}


来源:https://stackoverflow.com/questions/63881681/java-program-to-create-a-descending-order-using-bucket-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!