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 ]
堆排序:
function swap(A, i, j) { let temp = A[i] A[i] = A[j] A[j] = temp } function shiftDown(A, i, length) { let temp for (let j = 2 * i + 1; j < length; j = 2 * j + 1) { temp = A[i] if (j + 1 < length && A[j] > A[j + 1]) { j++ } if (temp > A[j]) { swap(A, i, j) i = j } else { break } } } function heapSort(A) { for (let i = Math.floor(A.length / 2 - 1); i >= 0; i--) { shiftDown(A, i, A.length) } for (let i = Math.floor(A.length - 1); i > 0; i--) { swap(A, 0, i) shiftDown(A, 0, i) } return A }
小顶堆topK:
function swap(A, i, j) { let temp = A[i] A[i] = A[j] A[j] = temp } function shiftDown(A, i, length) { let temp for (let j = 2 * i + 1; j < length; j = 2 * j + 1) { temp = A[i] if (j + 1 < length && A[j] > A[j + 1]) { j++ } if (temp > A[j]) { swap(A, i, j) i = j } else { break } } } function heapTopK(arr, k) { let A = arr.splice(0, k) for (let i = Math.floor(A.length / 2 - 1); i >= 0; i--) { shiftDown(A, i, A.length) } for (let i = 0; i < arr.length; i++) { if (arr[i] > A[0]) { A[0] = arr[i] for (let i = Math.floor(A.length / 2 - 1); i >= 0; i--) { shiftDown(A, i, A.length) } } } return A }