桶排序
- 时间复杂度:线性介,平均、最好为O(n+k),最坏为0(n^2)
- 空间复杂度:O(n+k)
- 稳定性:稳定性的前置条件是每个桶内使用的什么排序算法,如果使用的插入排序,那么桶排序是稳定的,如果使用的快排,那么是不稳定的(每个桶使用数组做举例)
算法解析:
- 空间换时间算法
- 首先规定好桶的数量
- 其次计算好每个桶的数据范围 (max-min+1)/bucketCount
- 把数据放在对应的桶里,桶内是排好序的
- 遍历每个桶,得到最后排好序的序列
动画演示:
动画来源于五分钟学算法,侵删
bucketSort
举例:
- 假设要统计一个班的语文成绩,分数从0-100 可以使用桶排序,固定10个桶
- 每个桶内的成绩 为 (10 * i) 到 (10 * i+9)
OC代码
- (NSArray *)bucketSort:(NSArray *)arr {
//固定桶数量为10个
int min = 0,max = 100,bucketCount = 10;
int range = (max-min+1)/bucketCount;//每个桶的数字范围
NSMutableArray *result = @[].mutableCopy;
NSMutableArray *bucketArr = @[].mutableCopy;
for (int i = 0; i<bucketCount; i++) {
[bucketArr addObject:[NSMutableArray array]];
}
for (int j = 0; j<arr.count; j++) {
int tmp = [arr[j] intValue];
int bucketIndex = floor((tmp-min)/range);//放到第几个桶
[bucketArr[bucketIndex] addObject:arr[j]];
}
for (int k = 0; k<bucketCount; k++) {
[self insertSort:bucketArr[k]];//对每个桶进行插入排序
for (int l = 0; l<((NSArray *)bucketArr[k]).count; l++) {
[result addObject:bucketArr[k][l]];
}
}
return result.copy;
}
Swift 代码
func bucketSort(arr:[Int],bucketCount:Int) -> Array<Int> {
let min = 0
let max = 100
let range = (max-min+1)/10
var result = [Int]()
var bucketArr:[Array<Int>] = []
for _ in 0..<bucketCount {
bucketArr.append([Int]())
}
for (_,item) in arr.enumerated() {
let index = (item-min)/range//放到哪个桶
bucketArr[index].append(item)
}
for i in 0..<bucketArr.count {
insertSort(&bucketArr[i])//每个桶排序
for (_,num) in bucketArr[i].enumerated() {
result.append(num)
}
}
return result
}
//插入排序
func insertSort(_ arr: inout [Int]) -> Void {
var current = 0
var preIndex = 0
for (index,item) in arr.enumerated() {
current = item
preIndex = index - 1
while(preIndex >= 0 && arr[preIndex] > current) {
arr[preIndex+1] = arr[preIndex]
preIndex -= 1;
}
arr[preIndex+1] = current
}
}
以下代码来源于网络,未验证
js实现
function bucketSort(arr, bucketSize) {
if (arr.length === 0) {
return arr;
}
var i;
var minValue = arr[0];
var maxValue = arr[0];
for (i = 1; i < arr.length; i++) {
if (arr[i] < minValue) {
minValue = arr[i]; // 输入数据的最小值
} else if (arr[i] > maxValue) {
maxValue = arr[i]; // 输入数据的最大值
}
}
//桶的初始化
var DEFAULT_BUCKET_SIZE = 5; // 设置桶的默认数量为5
bucketSize = bucketSize || DEFAULT_BUCKET_SIZE;
var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1;
var buckets = new Array(bucketCount);
for (i = 0; i < buckets.length; i++) {
buckets[i] = [];
}
//利用映射函数将数据分配到各个桶中
for (i = 0; i < arr.length; i++) {
buckets[Math.floor((arr[i] - minValue) / bucketSize)].push(arr[i]);
}
arr.length = 0;
for (i = 0; i < buckets.length; i++) {
insertionSort(buckets[i]); // 对每个桶进行排序,这里使用了插入排序
for (var j = 0; j < buckets[i].length; j++) {
arr.push(buckets[i][j]);
}
}
return arr;
}
java 实现
public class BucketSort implements IArraySort {
private static final InsertSort insertSort = new InsertSort();
@Override
public int[] sort(int[] sourceArray) throws Exception {
// 对 arr 进行拷贝,不改变参数内容
int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
return bucketSort(arr, 5);
}
private int[] bucketSort(int[] arr, int bucketSize) throws Exception {
if (arr.length == 0) {
return arr;
}
int minValue = arr[0];
int maxValue = arr[0];
for (int value : arr) {
if (value < minValue) {
minValue = value;
} else if (value > maxValue) {
maxValue = value;
}
}
int bucketCount = (int) Math.floor((maxValue - minValue) / bucketSize) + 1;
int[][] buckets = new int[bucketCount][0];
// 利用映射函数将数据分配到各个桶中
for (int i = 0; i < arr.length; i++) {
int index = (int) Math.floor((arr[i] - minValue) / bucketSize);
buckets[index] = arrAppend(buckets[index], arr[i]);
}
int arrIndex = 0;
for (int[] bucket : buckets) {
if (bucket.length <= 0) {
continue;
}
// 对每个桶进行排序,这里使用了插入排序
bucket = insertSort.sort(bucket);
for (int value : bucket) {
arr[arrIndex++] = value;
}
}
return arr;
}
private int[] arrAppend(int[] arr, int value) {
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = value;
return arr;
}
}
php代码实现
function bucketSort($arr, $bucketSize = 5)
{
if (count($arr) === 0) {
return $arr;
}
$minValue = $arr[0];
$maxValue = $arr[0];
for ($i = 1; $i < count($arr); $i++) {
if ($arr[$i] < $minValue) {
$minValue = $arr[$i];
} else if ($arr[$i] > $maxValue) {
$maxValue = $arr[$i];
}
}
$bucketCount = floor(($maxValue - $minValue) / $bucketSize) + 1;
$buckets = array();
for ($i = 0; $i < count($buckets); $i++) {
$buckets[$i] = [];
}
for ($i = 0; $i < count($arr); $i++) {
$buckets[floor(($arr[$i] - $minValue) / $bucketSize)][] = $arr[$i];
}
$arr = array();
for ($i = 0; $i < count($buckets); $i++) {
$bucketTmp = $buckets[$i];
sort($bucketTmp);
for ($j = 0; $j < count($bucketTmp); $j++) {
$arr[] = $bucketTmp[$j];
}
}
return $arr;
}
Python代码实现
def __init__(self, datas, size=100):
self.datas = datas
self.bucketSize = size
self.result = [0 for i in range(len(datas))]
self.bucket = [0 for i in range(self.bucketSize)]
def _sort(self):
# 读入各个元素,并在对应的位置统计,当bucket里的元素不为0
# 就保存到result里面
for num in self.datas:
self.bucket[num] += 1
j = 0
for i in range(self.bucketSize):
while(self.bucket[i]):
self.result[j] = i
self.bucket[i] -= 1
j += 1
def show(self):
print "Resutl is:",
for i in self.result:
print i,
print ''
go代码实现
func bucketSort(theArray []int,num int){
var theSort [99]int
for i:=0;i< len(theArray);i++{
theSort[10]=1
if theSort[theArray[i]] !=0{
theSort[theArray[i]] = theSort[theArray[i]]+1
}else{
theSort[theArray[i]] = 1
}
}
l:=list.New()
for j:=0;j<len(theSort);j++{
if theSort[j]==0{
//panic("error test.....")
}else{
for k:=0;k<theSort[j];k++{
l.PushBack(j)
}
}
}
for e := l.Front(); e != nil; e = e.Next() {
fmt.Print(e.Value, " ")
}
网友评论