-
-
Notifications
You must be signed in to change notification settings - Fork 414
/
Copy pathquick-sort.js
37 lines (32 loc) · 919 Bytes
/
quick-sort.js
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
module.exports = function quickSort (array, compare) {
var lesser = [],
greater = [],
pivot;
// Not an array, empty or array of 1 is already sorted
if (!Array.isArray(array) || 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)
);
};