面试面试算法十大经典排序算法之桶排序
云少十大经典排序算法之桶排序
master ,这是我的小站,欢迎访问哦~~
桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。为了使桶排序更加高效,我们需要做到这两点:
- 在额外空间充足的情况下,尽量增大桶的数量
- 使用的映射函数能够将输入的 N 个数据均匀的分配到 K 个桶中
同时,对于桶中元素的排序,选择何种比较排序算法对于性能的影响至关重要。
1. 什么时候最快
当输入的数据可以均匀的分配到每一个桶中。
2. 什么时候最慢
当输入的数据被分配到了同一个桶中。
3. JavaScript 代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| 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; 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; }
|
4. Java 代码实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
public class bucketSort { public void sort(Double[] a) { int n = a.length;
int bucketNum = 10; LinkedList<LinkedList<Double>> buckets = new LinkedList<LinkedList<Double>>(); for(int i = 0; i < bucketNum; i++){ LinkedList<Double> bucket = new LinkedList<Double>(); buckets.add(bucket); } for(int i = 0; i < n; i++){ int index = (int) (a[i] * bucketNum); buckets.get(index).add(a[i]); } int index = 0; for (LinkedList<Double> linkedList : buckets) { int size = linkedList.size(); if (size == 0) { continue; }
Double[] temp = new Double[size]; for (int i = 0; i < temp.length; i++) { temp[i] = linkedList.get(i); } new InsertSort().sort(temp); for (int i = 0; i < temp.length; i++) { a[index] = temp[i]; index++; } }
}
public static void main(String[] args) { Double[] a = new Double[]{0.3, 0.6, 0.5}; new BucketSort().sort(a); for (int i = 0; i < a.length; i++) { System.out.println(a[i]); } }
|