Skip to content

Commit

Permalink
Sorting Algorithms: BucketSort now accepts the sorter used for buckets
Browse files Browse the repository at this point in the history
Also decreased the amount of buckets created for its Animatable.
Best-case scenario each bucket should only contain at most 4 elements.
  • Loading branch information
Marco4413 committed Nov 15, 2024
1 parent 1c2f5e4 commit b9b384e
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions examples/007-sorting_algorithms/sorting.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,11 @@ export function* AnimatableHeapSort(array) {
/**
* @param {number[]} array Array of numbers in the range [0,1) with a uniform distribution
* @param {number} bucketCount If undefined = array.length
* @param {(array: any[], p: number, q: number, key: function, comparator: function) => void|Generator<number[][]>} bucketSorter
* Any sorter which accepts a range and key, comparator functions.
* If it's a Generator function, it must yield values which follow the standard of other sorters in this library.
*/
export function* BucketSort(array, bucketCount, key=(o => o), comparator=((a, b) => a-b)) {
export function* BucketSort(array, bucketCount, bucketSorter=InsertionSort, key=(o => o), comparator=((a, b) => a-b)) {
bucketCount = bucketCount ?? array.length;
if (array.length <= 1) return;

Expand Down Expand Up @@ -280,15 +283,23 @@ export function* BucketSort(array, bucketCount, key=(o => o), comparator=((a, b)
// InsertionSort is used by default because bucketCount = array.length
// Moreover, the numbers are uniformly distributed.
// Which means that bucket.length will always be small.
bucketSorts.push(InsertionSort(array, i-bucket.length, i, key, comparator));
const sorting = bucketSorter(array, i-bucket.length, i, key, comparator);
// Since bucketSorter may be chosen by the user, make sure it's a Generator.
// If so, push it into the list of all sorting generators.
if (sorting && sorting.next) {
bucketSorts.push(sorting);
}
}
}

yield* ZipActions(...bucketSorts);
}

export function* AnimatableBucketSort(array) {
yield* BucketSort(array);
// If the array is uniformly distributed, in the best-case scenario,
// there will be at most 4 elements in each bucket.
// Which InsertionSort should be able to handle quickly.
yield* BucketSort(array, Math.floor(array.length/4));
}

/**
Expand Down

0 comments on commit b9b384e

Please sign in to comment.