UNPKG

lgrthms

Version:

Algorithms and data structures for your JavaScript and TypeScript projects 🧑‍💻

70 lines (69 loc) 2.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.quickselectKthLargest = exports.quickselectKthSmallest = void 0; const arrays_1 = require("../../utils/arrays"); function quickselectKthSmallest(array, k, get) { if (k <= 0 || k > array.length) { return; } get = get ? get : (element) => element; const targetIdx = k - 1; let startIdx = 0; let endIdx = array.length - 1; while (startIdx <= endIdx) { const pivotIdx = doQuicksortAndGetPivotIdx(array, get, startIdx, endIdx); if (targetIdx === pivotIdx) { return array[pivotIdx]; } if (pivotIdx > targetIdx) { endIdx = pivotIdx - 1; } else { startIdx = pivotIdx + 1; } } } exports.quickselectKthSmallest = quickselectKthSmallest; function quickselectKthLargest(array, k, get) { if (k <= 0 || k > array.length) { return; } get = get ? get : (element) => element; const targetIdx = array.length - k; let startIdx = 0; let endIdx = array.length - 1; while (startIdx <= endIdx) { const pivotIdx = doQuicksortAndGetPivotIdx(array, get, startIdx, endIdx); if (targetIdx === pivotIdx) { return array[pivotIdx]; } if (pivotIdx > targetIdx) { endIdx = pivotIdx - 1; } else { startIdx = pivotIdx + 1; } } } exports.quickselectKthLargest = quickselectKthLargest; function doQuicksortAndGetPivotIdx(array, get, startIdx, endIdx) { const pivotIdx = startIdx; let leftIdx = pivotIdx + 1; let rightIdx = endIdx; while (leftIdx <= rightIdx) { const pivotValue = get(array[pivotIdx]); const leftValue = get(array[leftIdx]); const rightValue = get(array[rightIdx]); if (leftValue > pivotValue && rightValue < pivotValue) { (0, arrays_1.swap)(array, leftIdx, rightIdx); } if (leftValue <= pivotValue) { leftIdx++; } if (rightValue >= pivotValue) { rightIdx--; } } (0, arrays_1.swap)(array, pivotIdx, rightIdx); return rightIdx; }