bucket sort的原理是,在已知道需要排序的数值范围,分成几个水桶,把数值填入相应的水桶,同一个水桶内部,需要再排序(方法不限),最终在汇总各水桶的内容,返回。
通过实现算法,来熟悉基本的javascript..
<script>
/*按体重排序
入学儿童的体重
小于12kg 12kg-15kg 15kg-19kg 大于19kg
[{name:xiaoming, weight:17.3},{name:abc, weight:15.8},{name:youyou, weight:16}, {name:fatfat, weight:20}, {name:slim, weight:11},
{name:strong, weight:18}, {name:high, weight:13.5}, {name:fairy, weight: 12}, {name:twin, weight:12.1}, {name:twin, weight:12.1}];
*/
function bucketSort(arr)/*input is unsorted array, return the sorted array by weight, the arr objects' format is [{name:"abc", weight:10}, {name:"bbb", weight:15}]*/
{
var bucket = [[], [], [], []];//var bucket[4]; error, var bucket[], runtime error
var len = arr.length;
var curBucket;
var curChild;
var retArr = [];
for(var i = 0; i < len; i++)
{
curChild = arr[i];
var curWeight = curChild.weight;
if(curWeight < 12)
{
curBucket = bucket[0];
}
else if(curWeight < 15 && curWeight >= 12)
{
curBucket = bucket[1];
}
else if(curWeight < 19 && curWeight >= 15)
{
curBucket = bucket[2];
}
else if(curWeight >= 19)
{
curBucket = bucket[3];
}
var insertToBucket = function(lowBound, highBound){//sort by divide
if(highBound == lowBound)
curBucket.splice(lowBound, 0, curChild);
else
{
var mid = Math.floor((lowBound + highBound)/2);
if(curChild.weight < curBucket[mid].weight)
{
insertToBucket(lowBound, mid);
}
else{
insertToBucket(mid + 1, highBound);
}
}
};
insertToBucket(0, curBucket.length);
}
for(var i = 0; i < 4; i++)
{
curBucket = bucket[i];
len = curBucket.length;
for(var j = 0; j < len; j++)
{
retArr.push(curBucket[j]);
}
}
return retArr;
}
function printArray(arr)
{
arr.forEach(function(e){
console.log(e.name + ":" + e.weight + "\t");
});
}
var input = [{name:"xiaoming", weight:17.3},{name:"abc", weight:15.8},{name:"youyou", weight:16}, {name:"fatfat", weight:20}, {name:"slim", weight:11},
{name:"strong", weight:18}, {name:"high", weight:13.5}, {name:"fairy", weight: 12}, {name:"twin", weight:12.1}, {name:"twin", weight:12.1}];
printArray(input);
var output = bucketSort(input);
printArray(output);
</script>