【发布时间】:2023-04-19 18:14:01
【问题描述】:
请帮帮我,我真的想不通。我刚刚在互联网上找到了这个关于桶排序的代码,想知道它是否可以按降序排序?我尝试使用 reverse() 但它似乎不起作用它仍然以升序显示。
import java.util.*;
public class BucketSort {
public static void main(String[] args) {
int[] intArr = {47, 85, 10, 45, 16, 34, 67, 80, 34, 4, 0, 99};
//int[] intArr = {21,11,33,70,5,25,65,55};
System.out.println("Original array- " + Arrays.toString(intArr));
bucketSort(intArr, 10);
System.out.println("Sorted array after bucket sort- " + Arrays.toString(intArr));
}
private static void bucketSort(int[] intArr, int noOfBuckets){
// Create bucket array
List<Integer>[] buckets = new List[noOfBuckets];
// Associate a list with each index
// in the bucket array
for(int i = 0; i < noOfBuckets; i++){
buckets[i] = new LinkedList<>();
}
// Assign numbers from array to the proper bucket
// by using hashing function
for(int num : intArr){
//System.out.println("hash- " + hash(num));
buckets[hash(num)].add(num);
}
// sort buckets
for(List<Integer> bucket : buckets){
Collections.sort(bucket);
}
int i = 0;
// Merge buckets to get sorted array
for(List<Integer> bucket : buckets){
for(int num : bucket){
intArr[i++] = num;
}
}
}
// A very simple hash function
private static int hash(int num){
return num/10;
}
}
【问题讨论】:
-
你在哪里实际使用
reverse()?也许您应该将其添加到您的描述中。
标签: java arrays algorithm sorting bucket-sort