JS解决topK--快排、冒泡、大小堆顶

快排算法:

let quickSort = function (arr) {
    if (arr.length < 2) return arr
    let midValue = arr.splice(0, 1), left = [], right = []
    arr.forEach(el => {
        el > midValue ? right.push(el) : left.push(el)
    });
    return quickSort(left).concat(midValue, quickSort(right))
}
console.log(quickSort([6, 0, 1, 4, 9, 7, -3, 1, -4, -8, 4, -7, -3, 3, 2, -3, 9, 5, -4, 0]))
////[ -8, -7, -4, -4, -3, -3, -3, 0, 0, 1, 1, 2, 3, 4, 4, 5, 6, 7, 9, 9 ]

改造快排求topk:

let quickTopK = function (arr, k) {
    if(k==0)return []
    if (arr.length < 2) return arr
    let midValue = arr.splice(0, 1), left = [], right = []
    arr.forEach((el) => {
        el > midValue ? left.push(el) : right.push(el)
    });
    if (left.length == k) {
        return left
    } else if (left.length > k) {
        return quickTopK(left, k)
    } else {
        return left.concat(midValue, quickTopK(right, k - left.length - 1))
    }
}
console.log(quickTopK([6, 0, 1, 4, 9, 7, -3, 1, -4, -8, 4, -7, -3, 3, 2, -3, 9, 5, -4, 0], 8))
////[ 9, 7, 9, 6, 5, 4, 4, 3 ]

猜你喜欢

转载自www.cnblogs.com/ckAng/p/12390124.html