Quickselect
quickselect is a highly optimized, tiny JavaScript library implementing the Floyd-Rivest selection algorithm. It efficiently partially sorts an array in-place, ensuring that elements up to a specified index `k` are the smallest in the given range. The current stable version is 3.0.0, which was a significant update dropping CommonJS and UMD builds, making it exclusively ESM and requiring modern ES syntax. Releases appear to be infrequent, driven by significant architectural changes or feature additions. Its primary differentiator is its minimal footprint and speed for selection tasks compared to full sorting algorithms, making it ideal for scenarios where only a subset of sorted elements is needed.
Common errors
-
ReferenceError: require is not defined
cause Attempting to use CommonJS `require()` to import `quickselect` version 3.0.0 or later in an ESM environment.fixSwitch to ES module import syntax: `import quickselect from 'quickselect';`. -
SyntaxError: Unexpected token '...' (related to modern JavaScript features)
cause Running `quickselect` v3.0.0+ in an environment that does not fully support modern ES syntax without proper transpilation.fixEnsure your runtime environment supports modern JavaScript or configure your build pipeline (e.g., Babel, esbuild) to transpile `quickselect`.
Warnings
- breaking Version 3.0.0 dropped UMD build and full support for CommonJS, making the package ESM-only.
- breaking Version 3.0.0 uses modern ES syntax, which may break compatibility with older environments (e.g., IE11) without transpilation.
- gotcha Version 1.1.1 had issues with some Webpack builds due to the `module` field in `package.json`, which was later rectified.
Install
-
npm install quickselect -
yarn add quickselect -
pnpm add quickselect
Imports
- quickselect
const quickselect = require('quickselect');import quickselect from 'quickselect';
Quickstart
import quickselect from 'quickselect'; const arr = [65, 28, 59, 33, 21, 56, 22, 95, 50, 12, 90, 53, 28, 77, 39]; // Rearrange the array such that elements up to index 8 are the smallest. // The 8th element (0-indexed) will be the (8 - 0 + 1)th smallest value in the original array. quickselect(arr, 8); console.log(arr); // Expected output similar to: [39, 28, 28, 33, 21, 12, 22, 50, 53, 56, 59, 65, 90, 77, 95] // Note: The order of elements *before* k is not guaranteed, only that they are smaller than or equal to arr[k].