问题
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