quick-sort.js 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2011 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. if (typeof define !== 'function') {
  8. var define = require('amdefine')(module, require);
  9. }
  10. define(function (require, exports, module) {
  11. // It turns out that some (most?) JavaScript engines don't self-host
  12. // `Array.prototype.sort`. This makes sense because C++ will likely remain
  13. // faster than JS when doing raw CPU-intensive sorting. However, when using a
  14. // custom comparator function, calling back and forth between the VM's C++ and
  15. // JIT'd JS is rather slow *and* loses JIT type information, resulting in
  16. // worse generated code for the comparator function than would be optimal. In
  17. // fact, when sorting with a comparator, these costs outweigh the benefits of
  18. // sorting in C++. By using our own JS-implemented Quick Sort (below), we get
  19. // a ~3500ms mean speed-up in `bench/bench.html`.
  20. /**
  21. * Swap the elements indexed by `x` and `y` in the array `ary`.
  22. *
  23. * @param {Array} ary
  24. * The array.
  25. * @param {Number} x
  26. * The index of the first item.
  27. * @param {Number} y
  28. * The index of the second item.
  29. */
  30. function swap(ary, x, y) {
  31. var temp = ary[x];
  32. ary[x] = ary[y];
  33. ary[y] = temp;
  34. }
  35. /**
  36. * Returns a random integer within the range `low .. high` inclusive.
  37. *
  38. * @param {Number} low
  39. * The lower bound on the range.
  40. * @param {Number} high
  41. * The upper bound on the range.
  42. */
  43. function randomIntInRange(low, high) {
  44. return Math.round(low + (Math.random() * (high - low)));
  45. }
  46. /**
  47. * The Quick Sort algorithm.
  48. *
  49. * @param {Array} ary
  50. * An array to sort.
  51. * @param {function} comparator
  52. * Function to use to compare two items.
  53. * @param {Number} p
  54. * Start index of the array
  55. * @param {Number} r
  56. * End index of the array
  57. */
  58. function doQuickSort(ary, comparator, p, r) {
  59. // If our lower bound is less than our upper bound, we (1) partition the
  60. // array into two pieces and (2) recurse on each half. If it is not, this is
  61. // the empty array and our base case.
  62. if (p < r) {
  63. // (1) Partitioning.
  64. //
  65. // The partitioning chooses a pivot between `p` and `r` and moves all
  66. // elements that are less than or equal to the pivot to the before it, and
  67. // all the elements that are greater than it after it. The effect is that
  68. // once partition is done, the pivot is in the exact place it will be when
  69. // the array is put in sorted order, and it will not need to be moved
  70. // again. This runs in O(n) time.
  71. // Always choose a random pivot so that an input array which is reverse
  72. // sorted does not cause O(n^2) running time.
  73. var pivotIndex = randomIntInRange(p, r);
  74. var i = p - 1;
  75. swap(ary, pivotIndex, r);
  76. var pivot = ary[r];
  77. // Immediately after `j` is incremented in this loop, the following hold
  78. // true:
  79. //
  80. // * Every element in `ary[p .. i]` is less than or equal to the pivot.
  81. //
  82. // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
  83. for (var j = p; j < r; j++) {
  84. if (comparator(ary[j], pivot) <= 0) {
  85. i += 1;
  86. swap(ary, i, j);
  87. }
  88. }
  89. swap(ary, i + 1, j);
  90. var q = i + 1;
  91. // (2) Recurse on each half.
  92. doQuickSort(ary, comparator, p, q - 1);
  93. doQuickSort(ary, comparator, q + 1, r);
  94. }
  95. }
  96. /**
  97. * Sort the given array in-place with the given comparator function.
  98. *
  99. * @param {Array} ary
  100. * An array to sort.
  101. * @param {function} comparator
  102. * Function to use to compare two items.
  103. */
  104. exports.quickSort = function (ary, comparator) {
  105. doQuickSort(ary, comparator, 0, ary.length - 1);
  106. };
  107. });