排序算法--桶排序

桶排序:

const arr = [1,4,3,6,7,5,2,9,8,2,6,7,0,8,6]
// 假设需要排序的数字范围在0-10 则需要一个长度为11的空数组来统计每个数字出现的次数
const counter = new Array(11).fill(0)
arr.map(item => counter[item]++) 
console.log(counter) // [1, 1, 2, 1, 1, 1, 3, 2, 2, 1, 0] 
let res = []
counter.map((item,index) => {
    
    
	for(let i = 0; i < item; i++) {
    
    
		res.push(index)
	}
})
console.log(res)//  [0, 1, 2, 2, 3, 4, 5, 6, 6, 6, 7, 7, 8, 8, 9]

猜你喜欢

转载自blog.csdn.net/weixin_44670249/article/details/118019532