From d76298722f667f3a43f38fe29f77496fa6605ef5 Mon Sep 17 00:00:00 2001 From: Vladislav Khvostov Date: Tue, 26 Sep 2017 07:24:36 +0300 Subject: [PATCH] Create quicksort.js --- 04_quicksort/es6/quicksort.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 04_quicksort/es6/quicksort.js diff --git a/04_quicksort/es6/quicksort.js b/04_quicksort/es6/quicksort.js new file mode 100644 index 0000000..25e3ebc --- /dev/null +++ b/04_quicksort/es6/quicksort.js @@ -0,0 +1,18 @@ +const quickSort = (array) => { + if (array.length < 2) { + return array; + } + if (array.length === 2) { + // if first elem more than second will swap them and return it like new array. + return array[0] < array[1] ? array : [array[1], array[0]]; + } + + const pivot = array[0] + const itemsAreLessPivotSubArray = array.filter(item => item < pivot); + const itemsAreMoreThenPivotSubArray = array.filter(item => item > pivot); + + return [...quickSort(itemsAreLessPivotSubArray), pivot, ...quickSort(itemsAreMoreThenPivotSubArray)]; +}; + +module.exports = quickSort; +console.log(quicksort([10, 5, 2, 3])); // [2, 3, 5, 10]