Skip to content

Commit d762987

Browse files
vkhvegonSchiele
authored andcommitted
Create quicksort.js
1 parent 44f8151 commit d762987

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

04_quicksort/es6/quicksort.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
const quickSort = (array) => {
2+
if (array.length < 2) {
3+
return array;
4+
}
5+
if (array.length === 2) {
6+
// if first elem more than second will swap them and return it like new array.
7+
return array[0] < array[1] ? array : [array[1], array[0]];
8+
}
9+
10+
const pivot = array[0]
11+
const itemsAreLessPivotSubArray = array.filter(item => item < pivot);
12+
const itemsAreMoreThenPivotSubArray = array.filter(item => item > pivot);
13+
14+
return [...quickSort(itemsAreLessPivotSubArray), pivot, ...quickSort(itemsAreMoreThenPivotSubArray)];
15+
};
16+
17+
module.exports = quickSort;
18+
console.log(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]

0 commit comments

Comments
 (0)