十大排序算法之五 - 桶排序
1.桶排序的介绍
-
桶排序同样是一种线性时间的排序算法
-
桶排序需要创建若干个桶来协助排序,每一个桶(bucket)代表一个区间范围,里面可以承载一个或多个元素
-
桶排序的第1步,就是创建这些桶,并确定每一个桶的区间范围具体需要建立多少个桶,如何确定桶的区间范围,有很多种不同的方式。我们这里创建的桶数量等于原始数列的元素数量,除最后一个桶只包含数列最大值外, 前面各个桶的区间按照比例来确定
-
区间跨度 = (最大值-最小值)/ (桶的数量 - 1)
-
假设有一个非整数数列如下:4.5,0.84,3.25,2.18,0.5
2.Java实现桶排序
package com.lagou.bucketSort;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
/**
* @author 云梦归遥
* @date 2022/5/18 12:06
* @description 桶排序
*/
public class BucketSortMethod {
public double[] bucketSort(double[] array){
double min = 0, max = 0; // 数组中的最大,最小值
for (int i = 0; i < array.length; i++){
if (array[i] > max) max = array[i];
if (array[i] < min) min = array[i];
}
// 定义桶
double minToMax = max - min; // 最大最小之间的差值
int bucketNum = array.length; // 桶的数量就是数组的长度
ArrayList<LinkedList<Double>> bucketList = new ArrayList<>();
// 初始化每个桶
for (int i = 0; i < array.length; i++){
bucketList.add(new LinkedList<Double>());
}
// 向桶中存放元素
for (int i = 0; i < array.length; i++){
int bucketIndex = (int)((array[i] - min) * (bucketNum - 1) / minToMax);
bucketList.get(bucketIndex).add(array[i]);
}
// 对每个桶进行排序
for (int i = 0; i < bucketList.size(); i++){
LinkedList<Double> doubleLinkedList = bucketList.get(i);
if (doubleLinkedList.size() > 1){
Collections.sort(doubleLinkedList);
}
}
// 构建结果数组
double[] arrayResult = new double[array.length];
int index = 0;
for (LinkedList<Double> linkedList: bucketList){
if (linkedList.size() > 0){
for (Double num: linkedList){
arrayResult[index++] = num;
}
}
}
return arrayResult;
}
}
进行测试
package com.lagou.bucketSort.test;
import com.lagou.bucketSort.BucketSortMethod;
import java.util.Arrays;
/**
* @author 云梦归遥
* @date 2022/5/18 12:44
* @description 桶排序测试
*/
public class BucketSortTest {
public static void main(String[] args) {
BucketSortMethod bucketSortMethod = new BucketSortMethod();
double[] array = {4.12, 6.421, 0.0023, 3.0, 2.123, 8.122, 4.12, 10.09};
System.out.println("【桶排序 - 前】" + Arrays.toString(array));
double[] doubles = bucketSortMethod.bucketSort(array);
System.out.println("【桶排序 - 后】" + Arrays.toString(doubles));
}
}
3.总结
- 时间复杂度:O(n)