Java 使用桶排序创建降序的程序
Java program to create a Descending Order using bucket sort
我正在编写一个程序来获取 10 个用户输入值 (1-100) 并使用桶排序根据用户偏好按升序或降序对其进行排序。我能够创建升序。这是我的升序代码,但我怎样才能让它降序呢?
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());
请记住,将桶组合到数组中时必须颠倒桶的顺序:
for(int index = buckets.length - 1; index >= 0; index--) {
for (int num: buckets[index]){
array[i++] = num;
}
我正在编写一个程序来获取 10 个用户输入值 (1-100) 并使用桶排序根据用户偏好按升序或降序对其进行排序。我能够创建升序。这是我的升序代码,但我怎样才能让它降序呢?
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());
请记住,将桶组合到数组中时必须颠倒桶的顺序:
for(int index = buckets.length - 1; index >= 0; index--) {
for (int num: buckets[index]){
array[i++] = num;
}