From fe800d4e028c24e8614045357b0ee793deb9ef92 Mon Sep 17 00:00:00 2001 From: Isabelle Viktoria Maciohsek Date: Mon, 28 Dec 2020 22:11:56 +0200 Subject: [PATCH] Add bucketSort --- snippets/bucketSort.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 snippets/bucketSort.md diff --git a/snippets/bucketSort.md b/snippets/bucketSort.md new file mode 100644 index 000000000..56cde5756 --- /dev/null +++ b/snippets/bucketSort.md @@ -0,0 +1,32 @@ +--- +title: bucketSort +tags: algorithm,array,intermediate +--- + +Sorts an array of numbers, using the bucket sort algorithm. + +- Use `Math.min(),` `Math.max()` and the spread operator (`...`) to find the minimum and maximum values of the given array. +- Use `Array.from()` and `Math.floor()` to create the appropriate number of `buckets` (empty arrays). +- Use `Array.prototype.forEach()` to populate each bucket with the appropriate elements from the array. +- Use `Array.prototype.reduce()`, the spread operator (`...`) and `Array.prototype.sort()` to sort each bucket and append it to the result. + +```js +const bucketSort = (arr, size = 5) => { + const min = Math.min(...arr); + const max = Math.max(...arr); + const buckets = Array.from( + { length: Math.floor((max - min) / size) + 1 }, + () => [] + ); + + arr.forEach(val => { + buckets[Math.floor((val - min) / size)].push(val); + }); + + return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []); +}; +``` + +```js +bucketSort([6, 3, 4, 1]); // [1, 3, 4, 6] +```