桶排序算法 Java代码
时间: 2024-04-07 21:19:12 浏览: 74
public class BucketSort {
public static void bucketSort(int[] nums) {
int maxVal = Integer.MIN_VALUE;
for (int num : nums) {
maxVal = Math.max(maxVal, num);
}
int[] bucket = new int[maxVal + 1];
for (int num : nums) {
bucket[num]++;
}
int index = 0;
for (int i = 0; i < bucket.length; i++) {
for (int j = 0; j < bucket[i]; j++) {
nums[index++] = i;
}
}
}
public static void main(String[] args) {
int[] nums = {5, 3, 2, 8, 6, 4, 9};
bucketSort(nums);
System.out.println(Arrays.toString(nums));
}
}
相关问题
桶排序算法java代码
以下是桶排序算法的Java代码实现:
public static int[] bucketSort(int[] array, int bucketSize) {
if (array.length == 0) {
return array;
}
// 找到最大值和最小值
int minValue = array;
int maxValue = array;
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
} else if (array[i] > maxValue) {
maxValue = array[i];
}
}
// 计算桶的数量
int bucketCount = (maxValue - minValue) / bucketSize + 1;
ArrayList<ArrayList<Integer>> buckets = new ArrayList<>(bucketCount);
for (int i = 0; i < bucketCount; i++) {
buckets.add(new ArrayList<>());
}
// 将元素分配到桶中
for (int i = 0; i < array.length; i++) {
int bucketIndex = (array[i] - minValue) / bucketSize;
buckets.get(bucketIndex).add(array[i]);
}
// 对每个桶中的元素进行排序
int currentIndex = 0;
for (int i = 0; i < buckets.size(); i++) {
ArrayList<Integer> bucket = buckets.get(i);
if (bucket.size() == 0) {
continue;
}
int[] bucketArray = new int[bucket.size()];
for (int j = 0; j < bucket.size(); j++) {
bucketArray[j] = bucket.get(j);
}
int[] sortedBucket = bubbleSort(bucketArray);
for (int j = 0; j < sortedBucket.length; j++) {
array[currentIndex++] = sortedBucket[j];
}
}
return array;
}
其中,bubbleSort是冒泡排序算法的实现。
桶排序的java算法怎么写
桶排序的java算法可以使用下面的代码实现:// Java program to sort an array using bucket sort
public class BucketSort {
// Function to sort arr[] of size n using bucket sort
static void bucketSort(float arr[], int n)
{
// 1) Create n empty buckets
@SuppressWarnings("unchecked")
ArrayList<Float>[] buckets = new ArrayList[n];
for (int i = 0; i < n; i++)
阅读全文