Skip to content

Commit 704669a

Browse files
author
mik-laj
committed
Add a comparator and improve code style
1 parent c5b7a31 commit 704669a

File tree

2 files changed

+41
-10
lines changed

2 files changed

+41
-10
lines changed

src/sorting/quicksort-functional.js

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,35 +2,66 @@
22

33
'use strict';
44

5+
function compare(a, b) {
6+
return a - b;
7+
}
8+
59
/**
6-
* The quicksort algorithm (functional variant). It's complexity is O(nlog n).
10+
* Quicksort algorithm (functional variant)
711
*
812
* @public
13+
* @param {array} array Array which should be sorted.
14+
* @return {array} Sorted array.
915
*/
1016
var quickSort = (function () {
1117

1218
/**
13-
* Sorts given array.
19+
* Recursively calls itself.
1420
*
1521
* @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
1823
*/
19-
return function quickSort(array, left, right, cmp) {
20-
if ( arr.length < 1) {
24+
return function quickSort(array, cmp) {
25+
if (arr.length < 1) {
2126
return arr;
2227
}
2328

24-
var [x, ...rest] = arr;
29+
const [x, ...rest] = arr;
2530

2631
return [
27-
...quickSort(rest.filter(v => v <= x)),
32+
...quickSort(rest.filter(v => cmp(v, x) < 0),
2833
x,
29-
...quickSort(rest.filter(v => v > x))
34+
...quickSort(rest.filter(v => cmp(v, x) >= 0))
3035
]
3136
return array;
3237
}
3338

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+
3465
}());
3566

3667
exports.quickSort = quickSort;

test/sorting/quicksort-functional.spec.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@ var sortTestCase = require('./sort.testcase.js');
22
var quickSort =
33
require('../../src/sorting/quicksort-functional.js').quickSort;
44

5-
sortTestCase(quickSort, 'Quick sort', { reverse: false });
5+
sortTestCase(quickSort, 'Quick sort');

0 commit comments

Comments
 (0)