quickSelect.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /**
  2. * Quick select n-th element in an array.
  3. *
  4. * Note: it will change the elements placement in array.
  5. *
  6. * @module echarts/core/quickSelect
  7. * @author Yi Shen(https://github.com/pissang)
  8. */
  9. function defaultCompareFunc(a, b) {
  10. return a - b;
  11. }
  12. function swapElement(arr, idx0, idx1) {
  13. var tmp = arr[idx0];
  14. arr[idx0] = arr[idx1];
  15. arr[idx1] = tmp;
  16. }
  17. function select(arr, left, right, nth, compareFunc) {
  18. var pivotIdx = left;
  19. var pivotValue;
  20. while (right > left) {
  21. pivotIdx = Math.round((right + left) / 2);
  22. pivotValue = arr[pivotIdx]; // Swap pivot to the end
  23. swapElement(arr, pivotIdx, right);
  24. pivotIdx = left;
  25. for (var i = left; i <= right - 1; i++) {
  26. if (compareFunc(pivotValue, arr[i]) >= 0) {
  27. swapElement(arr, i, pivotIdx);
  28. pivotIdx++;
  29. }
  30. }
  31. swapElement(arr, right, pivotIdx);
  32. if (pivotIdx === nth) {
  33. return pivotIdx;
  34. } else if (pivotIdx < nth) {
  35. left = pivotIdx + 1;
  36. } else {
  37. right = pivotIdx - 1;
  38. }
  39. } // Left == right
  40. return left;
  41. }
  42. /**
  43. * @alias module:echarts/core/quickSelect
  44. * @param {Array} arr
  45. * @param {number} [left]
  46. * @param {number} [right]
  47. * @param {number} nth
  48. * @param {Function} [compareFunc]
  49. * @example
  50. * var quickSelect = require('echarts/core/quickSelect');
  51. * var arr = [5, 2, 1, 4, 3]
  52. * quickSelect(arr, 3);
  53. * quickSelect(arr, 0, 3, 1, function (a, b) {return a - b});
  54. *
  55. * @return {number}
  56. */
  57. function _default(arr, left, right, nth, compareFunc) {
  58. if (arguments.length <= 3) {
  59. nth = left;
  60. if (arguments.length == 2) {
  61. compareFunc = defaultCompareFunc;
  62. } else {
  63. compareFunc = right;
  64. }
  65. left = 0;
  66. right = arr.length - 1;
  67. }
  68. return select(arr, left, right, nth, compareFunc);
  69. }
  70. module.exports = _default;