|
2 | 2 |
|
3 | 3 | 'use strict';
|
4 | 4 |
|
| 5 | + function compare(a, b) { |
| 6 | + return a - b; |
| 7 | + } |
| 8 | + |
5 | 9 | /**
|
6 |
| - * The quicksort algorithm (functional variant). It's complexity is O(nlog n). |
| 10 | + * Quicksort algorithm (functional variant) |
7 | 11 | *
|
8 | 12 | * @public
|
| 13 | + * @param {array} array Array which should be sorted. |
| 14 | + * @return {array} Sorted array. |
9 | 15 | */
|
10 | 16 | var quickSort = (function () {
|
11 | 17 |
|
12 | 18 | /**
|
13 |
| - * Sorts given array. |
| 19 | + * Recursively calls itself. |
14 | 20 | *
|
15 | 21 | * @private
|
16 |
| - * @param {array} array Array which should be sorted |
17 |
| - * @returns {array} array Sorted array |
| 22 | + * @param {array} array Array which should be processed |
18 | 23 | */
|
19 |
| - return function quickSort(array, left, right, cmp) { |
20 |
| - if ( arr.length < 1) { |
| 24 | + return function quickSort(array, cmp) { |
| 25 | + if (arr.length < 1) { |
21 | 26 | return arr;
|
22 | 27 | }
|
23 | 28 |
|
24 |
| - var [x, ...rest] = arr; |
| 29 | + const [x, ...rest] = arr; |
25 | 30 |
|
26 | 31 | return [
|
27 |
| - ...quickSort(rest.filter(v => v <= x)), |
| 32 | + ...quickSort(rest.filter(v => cmp(v, x) < 0), |
28 | 33 | x,
|
29 |
| - ...quickSort(rest.filter(v => v > x)) |
| 34 | + ...quickSort(rest.filter(v => cmp(v, x) >= 0)) |
30 | 35 | ]
|
31 | 36 | return array;
|
32 | 37 | }
|
33 | 38 |
|
| 39 | + |
| 40 | + /** |
| 41 | + * Quicksort algorithm. In this version of quicksort used |
| 42 | + * functional programming mechanisms.<br><br> |
| 43 | + * Time complexity: O(N log(N)). |
| 44 | + * |
| 45 | + * @example |
| 46 | + * |
| 47 | + * var sort = require('path-to-algorithms/src' + |
| 48 | + * '/sorting/quicksort-functional').quickSort; |
| 49 | + * console.log(sort([2, 5, 1, 0, 4])); // [ 0, 1, 2, 4, 5 ] |
| 50 | + * |
| 51 | + * @public |
| 52 | + * @module sorting/quicksort-functional |
| 53 | + * @param {Array} array Input array. |
| 54 | + * @param {Function} cmp Optional. A function that defines an |
| 55 | + * alternative sort order. The function should return a negative, |
| 56 | + * zero, or positive value, depending on the arguments. |
| 57 | + * @return {Array} Sorted array. |
| 58 | + */ |
| 59 | + return function (array, cmp) { |
| 60 | + cmp = cmp || compare; |
| 61 | + quicksort(array, 0, array.length - 1, cmp); |
| 62 | + return array; |
| 63 | + }; |
| 64 | + |
34 | 65 | }());
|
35 | 66 |
|
36 | 67 | exports.quickSort = quickSort;
|
|
0 commit comments