本文介绍了Java程序使用存储桶排序创建降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个程序,以获取10个用户输入值(1-100),并使用存储桶排序将其根据用户喜好按升序或降序进行排序.我能够创建升序.这是我的升序代码,但是如何使它降序呢?
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;
}
}
推荐答案
尝试以下操作:
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;
}
这篇关于Java程序使用存储桶排序创建降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!