From 9f6768392c85678356d85ae62654fc9588cd80fb Mon Sep 17 00:00:00 2001 From: xqdoo00o Date: Thu, 28 Dec 2017 19:19:33 +0800 Subject: [PATCH] Create arrayQuickSort.md --- snippets/arrayQuickSort.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 snippets/arrayQuickSort.md diff --git a/snippets/arrayQuickSort.md b/snippets/arrayQuickSort.md new file mode 100644 index 000000000..cbc5f73c0 --- /dev/null +++ b/snippets/arrayQuickSort.md @@ -0,0 +1,21 @@ +### ArrayQuickSort + +QuickSort an Array (ascending sort by default). + +Use recursion. Use `Array.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it. If the parameter `desc` is truthy, return array sorts in descending order. + +```js +const quickSort = ([n, ...nums], desc) => + isNaN(n) + ? [] + : [ + ...quickSort(nums.filter(v => desc ? v > n : v <= n), desc), + n, + ...quickSort(nums.filter(v =>!desc ? v > n : v <= n), desc) + ] +``` + +```js +quickSort([4,1,3,2,]); // [1,2,3,4] +quickSort([4,1,3,2,],true); // [4,3,2,1] +```