Introduction
In this lab, we will explore the bucket sort algorithm in JavaScript. Bucket sort is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Each bucket is then sorted individually, either using a different sorting algorithm or by recursively applying the bucket sorting algorithm. This lab will provide you with an opportunity to implement this algorithm and gain a deeper understanding of how it works.
Bucket Sort Algorithm
To use the bucket sort algorithm and sort an array of numbers, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Find the minimum and maximum values of the given array using
Math.min(),Math.max()and the spread operator (...). - Create the appropriate number of
buckets(empty arrays) usingArray.from()andMath.floor(). - Populate each bucket with the appropriate elements from the array using
Array.prototype.forEach(). - Sort each bucket and append it to the result using
Array.prototype.reduce(), the spread operator (...) andArray.prototype.sort().
Here is an example implementation of the bucket sort algorithm in JavaScript:
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)], []);
};
To test the algorithm, run the following code:
bucketSort([6, 3, 4, 1]); // [1, 3, 4, 6]
Summary
Congratulations! You have completed the Bucket Sort lab. You can practice more labs in LabEx to improve your skills.