桶排序算法
桶排序算法(Bucket Sort)是一种用于将元素排序的算法。该算法适用于输入数据分布比较均匀的情形。实现桶排序需要一个桶,即一个数组,需要满足以下两个条件:
- 桶的大小需要能够容纳待排序的所有元素;
- 所有元素必须是非负整数。
作用:
桶排序算法的主要目的是将数据从未排序的状态转换为有序的状态。
使用方法:
1.计算待排序的序列的最大值,创建一个长度等于最大值加一的桶;
2.遍历序列,将对应的元素值作为桶的索引,桶对应的元素值加一;
3.遍历桶,将索引值作为元素值,元素值即对应的数量,遍历次数为桶的大小。
下面是排序一个随机序列的例子:
const bucketSort = (array) => {
if (array.length === 0) {
return array;
}
const max = Math.max(...array);
const min = Math.min(...array);
const bucketsSize = Math.floor((max - min) / array.length) + 1;
const buckets = new Array(bucketsSize);
for (let i = 0; i < buckets.length; i++) {
buckets[i] = [];
}
for (let i = 0; i < array.length; i++) {
let buck = Math.floor((array[i] - min) / bucketsSize);
buckets[buck].push(array[i]);
}
array.length = 0;
for (let i = 0; i < buckets.length; i++) {
insertionSort(buckets[i]);
for (let j = 0; j < buckets[i].length; j++) {
array.push(buckets[i][j]);
}
}
return array;
};
const insertionSort = (array) => {
const length = array.length;
for (let i = 1; i < length; i++) {
let j = i - 1;
let temp = array[i];
while (j >= 0 && array[j] > temp) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp;
}
return array;
};
const data = [30, 20, 10, 60, 50, 40];
console.log("Before Sorted:", data);
console.log("After Sorted:", bucketSort(data));
以上代码首先确定桶的大小(bucketsSize),然后创建一个数量等于桶的大小的桶数组,遍历待排序的数组并将其放到对应的桶中。最后,对每个桶进行排序,然后再将排序好的元素重构为一个数组返回。
下面再给出一个统计一个英语文章中每个单词的出现次数的例子:
const bucketSort = (obj) => {
let bucket = [];
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
let index = Math.floor(obj[prop] * 100);
if (!bucket[index]) {
bucket[index] = [];
}
bucket[index].push(prop);
}
}
let result = [];
for (let i = bucket.length - 1; i >= 0; i--) {
if (bucket[i]) {
result.push(...bucket[i]);
}
}
return result;
};
const countWords = (text) => {
const words = text.toLowerCase().replace(/[^\w\s]/g, "").split(/\s+/);
const obj = {};
for (let i = 0; i < words.length; i++) {
if (obj[words[i]]) {
obj[words[i]]++;
} else {
obj[words[i]] = 1;
}
}
return bucketSort(obj);
};
const text = "The quick brown fox jumps over the lazy dog";
console.log(countWords(text));
以上代码首先将文章中的每个单词以及它们出现的次数保存在一个对象(obj)中,在对于每个单词,计算它占所有单词数的百分比,并保存在对应的桶中,最后遍历每个桶获取所有单词,并返回它们的有序数组。
以上两个例子展示了桶排序算法的两种实际应用,需要根据具体的情况选择使用哪种方式。