forked from blakeembrey/code-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquick-sort.js
More file actions
44 lines (36 loc) · 992 Bytes
/
Copy pathquick-sort.js
File metadata and controls
44 lines (36 loc) · 992 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
'use strict';
module.exports = function quickSort(input, compare) {
var lesser = [],
greater = [],
pivot;
if (!Array.isArray(input)) {
throw new Error('Can only sort arrays.');
}
var array = input.slice(0); // make a copy of the array
if (array.length < 2) {
return array;
}
// Create a compare func if not passed in
if (typeof compare !== 'function') {
compare = function (a, b) {
return a > b ? 1 : -1;
};
}
// Get our pivot, this can be random
pivot = array.splice(~~(Math.random() * array.length), 1);
// Iterate and put vals into either lesser or greater lists compared
// to the pivot
for (var i = 0; i < array.length; i++) {
if (compare(array[i], pivot) < 1) {
lesser.push(array[i]);
} else {
greater.push(array[i]);
}
}
// Sort lesser and greater lists, concat results
return Array.prototype.concat(
quickSort(lesser, compare),
pivot,
quickSort(greater, compare)
);
};