a62695fed9164ca0814d1bfffe2cb24a8278f5a3.svn-base 2.2 KB

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