Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions sorts/bucket_sort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/**
* @function bucketSort
* @description 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 either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
* @complexity_analysis
* Space Complexity - O(n + k)
* Time Complexity - O(n + k)
* @param {number[]} arr - The array to be sorted.
* @returns {number[]} - The sorted array.
* @see https://en.wikipedia.org/wiki/Bucket_sort
* @example bucketSort([5, 4, 3, 2, 1]) // [1, 2, 3, 4, 5]
*/

import { insertionSort } from "./insertion_sort";

export function bucketSort(arr: number[]): number[] {
const buckets: number[][] = [];
const sortedArray: number[] = [];

for (let i = 0; i < arr.length; i++) {
const bucketIndex = Math.floor(arr[i] / 10);
if (buckets[bucketIndex]) {
buckets[bucketIndex].push(arr[i]);
} else {
buckets[bucketIndex] = [arr[i]];
}
}

for (let i = 0; i < buckets.length; i++) {
if (buckets[i]) {
insertionSort(buckets[i]);
sortedArray.push(...buckets[i]);
}
}

return sortedArray;
}
21 changes: 21 additions & 0 deletions sorts/test/bucket_sort.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { bucketSort } from "../bucket_sort";

describe("Testing Bucket sort", () => {
const testCases: number[][] = [];

for (let i = 0; i < 10; i++) {
const arr = [];
for (let j = 0; j < 100; j++) {
arr.push(Math.floor(Math.random() * 100));
}
testCases.push(arr);
}
test.each(testCases)(
"should return the correct value for test case: %#",
(...arr: number[]) => {
expect(bucketSort([...arr])).toStrictEqual(
[...arr].sort((a: number, b: number) => a - b)
);
}
);
});