Guest User

Untitled

a guest
Dec 3rd, 2025
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | Source Code | 0 0
  1. Below is a **robust, iterative QuickSort in JavaScript** that:
  2.  
  3. * Works for **large arrays** (1M+ elements)
  4. * Supports a **custom comparator**
  5. * Avoids recursion → **prevents call-stack overflow**
  6. * Uses **Hoare partition** (fast and stable for large datasets)
  7.  
  8. ```js
  9. /**
  10. * QuickSort (iterative) with custom comparator
  11. * @param {Array} arr - array to sort
  12. * @param {(a: any, b: any) => number} cmp - comparator: <0 if a<b, >0 if a>b, 0 otherwise
  13. * @returns {Array} the sorted array (sorted in place)
  14. */
  15. function quickSort(arr, cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0)) {
  16. if (!Array.isArray(arr) || arr.length <= 1) return arr;
  17.  
  18. // Stack of [left, right] index pairs
  19. const stack = [[0, arr.length - 1]];
  20.  
  21. while (stack.length) {
  22. const [left, right] = stack.pop();
  23. if (left >= right) continue;
  24.  
  25. // Hoare partition
  26. const pivot = arr[Math.floor((left + right) / 2)];
  27. let i = left - 1;
  28. let j = right + 1;
  29.  
  30. while (true) {
  31. do { i++; } while (cmp(arr[i], pivot) < 0);
  32. do { j--; } while (cmp(arr[j], pivot) > 0);
  33.  
  34. if (i >= j) break;
  35. [arr[i], arr[j]] = [arr[j], arr[i]];
  36. }
  37.  
  38. // j is the partition index
  39. // Push the larger segment first to minimize stack size
  40. if (j - left < right - (j + 1)) {
  41. stack.push([j + 1, right], [left, j]);
  42. } else {
  43. stack.push([left, j], [j + 1, right]);
  44. }
  45. }
  46.  
  47. return arr;
  48. }
  49.  
  50. // Example usage:
  51. const arr = Array.from({ length: 1e6 }, () => Math.random());
  52. quickSort(arr, (a, b) => a - b);
  53.  
  54. console.log("Sorted?", arr[0] <= arr[1]);
  55. ```
  56.  
  57. ---
  58.  
  59. ### Notes for Handling ~1M Elements
  60.  
  61. ✔ **Iterative design**
  62. Avoids recursion depth issues typical in JS engines (which usually crash around 10k–30k nested calls).
  63.  
  64. ✔ **Hoare partition**
  65. More cache-friendly and faster for large arrays than Lomuto; fewer swaps.
  66.  
  67. ✔ **Comparator flexibility**
  68. You can pass any `cmp(a, b)` function:
  69.  
  70. ```js
  71. quickSort(users, (a, b) => a.age - b.age);
  72. quickSort(strings, (a, b) => a.localeCompare(b));
  73. ```
  74.  
  75. ---
  76.  
  77. If you want, I can also provide:
  78.  
  79. * A multi-threaded Web Worker version
  80. * A hybrid QuickSort + Insertion Sort (faster for partially sorted data)
  81. * A version optimized for objects with a `key` selector function
  82.  
Advertisement
Add Comment
Please, Sign In to add comment