Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Below is a **robust, iterative QuickSort in JavaScript** that:
- * Works for **large arrays** (1M+ elements)
- * Supports a **custom comparator**
- * Avoids recursion → **prevents call-stack overflow**
- * Uses **Hoare partition** (fast and stable for large datasets)
- ```js
- /**
- * QuickSort (iterative) with custom comparator
- * @param {Array} arr - array to sort
- * @param {(a: any, b: any) => number} cmp - comparator: <0 if a<b, >0 if a>b, 0 otherwise
- * @returns {Array} the sorted array (sorted in place)
- */
- function quickSort(arr, cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {
- if (!Array.isArray(arr) || arr.length <= 1) return arr;
- // Stack of [left, right] index pairs
- const stack = [[0, arr.length - 1]];
- while (stack.length) {
- const [left, right] = stack.pop();
- if (left >= right) continue;
- // Hoare partition
- const pivot = arr[Math.floor((left + right) / 2)];
- let i = left - 1;
- let j = right + 1;
- while (true) {
- do { i++; } while (cmp(arr[i], pivot) < 0);
- do { j--; } while (cmp(arr[j], pivot) > 0);
- if (i >= j) break;
- [arr[i], arr[j]] = [arr[j], arr[i]];
- }
- // j is the partition index
- // Push the larger segment first to minimize stack size
- if (j - left < right - (j + 1)) {
- stack.push([j + 1, right], [left, j]);
- } else {
- stack.push([left, j], [j + 1, right]);
- }
- }
- return arr;
- }
- // Example usage:
- const arr = Array.from({ length: 1e6 }, () => Math.random());
- quickSort(arr, (a, b) => a - b);
- console.log("Sorted?", arr[0] <= arr[1]);
- ```
- ---
- ### Notes for Handling ~1M Elements
- ✔ **Iterative design**
- Avoids recursion depth issues typical in JS engines (which usually crash around 10k–30k nested calls).
- ✔ **Hoare partition**
- More cache-friendly and faster for large arrays than Lomuto; fewer swaps.
- ✔ **Comparator flexibility**
- You can pass any `cmp(a, b)` function:
- ```js
- quickSort(users, (a, b) => a.age - b.age);
- quickSort(strings, (a, b) => a.localeCompare(b));
- ```
- ---
- If you want, I can also provide:
- * A multi-threaded Web Worker version
- * A hybrid QuickSort + Insertion Sort (faster for partially sorted data)
- * A version optimized for objects with a `key` selector function
Advertisement
Add Comment
Please, Sign In to add comment