/** * 在arr[l..h]中查找top k * @param {Array} arr * @param {Number} l * @param {Number} h * @param {Number} k */ functiontopKRange(arr, l, h, k) { if (l >= h) return;
const m = partition(arr, l, h);
if (m - l + 1 === k) { return; }
if (m - l + 1 > k) { topKRange(arr, l, m - 1, k); } else { topKRange(arr, m + 1, h, k - (m - l + 1)); } }
/** * partition arr by the last element * @param {Array} arr * @param {Number} l * @param {Number} h * @returns index of the partition element */ functionpartition(arr, l, h) { let i = l; let j = l;
while (j < h) { if (arr[j] > arr[h]) { swapArrEle(arr, i++, j++); } else { j++; } }
swapArrEle(arr, i, h); return i; }
functionswapArrEle(arr, i, j) { if (i === j) return;