Skip to content

Commit d1caf49

Browse files
committed
modify javascript quick-sort to copy input
otherwise, input parameter is changed.
1 parent 8fed565 commit d1caf49

File tree

1 file changed

+7
-3
lines changed

1 file changed

+7
-3
lines changed

solutions/javascript/quick-sort.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
module.exports = function quickSort (array, compare) {
1+
'use strict';
2+
3+
module.exports = function quickSort(input, compare) {
24
var lesser = [],
35
greater = [],
46
pivot;
57

68
// Not an array, empty or array of 1 is already sorted
7-
if (!Array.isArray(array) || array.length < 2) {
8-
return array;
9+
if (!Array.isArray(input) || input.length < 2) {
10+
return input;
911
}
1012

1113
// Create a compare func if not passed in
@@ -15,6 +17,8 @@ module.exports = function quickSort (array, compare) {
1517
};
1618
}
1719

20+
var array = input.slice(0); // make a copy of the array
21+
1822
// Get our pivot, this can be random
1923
pivot = array.splice(~~(Math.random() * array.length), 1);
2024

0 commit comments

Comments
 (0)