Skip to content

Commit 3ae40ff

Browse files
committed
Feat: Added bucket sort
1 parent b1ac5d6 commit 3ae40ff

2 files changed

Lines changed: 58 additions & 0 deletions

File tree

sorts/bucket_sort.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @function bucketSort
3+
* @description Bucket sort is a sorting algorithm that works by distributing the elements of an array into a number of buckets.
4+
* Each bucket is then sorted either using a different sorting algorithm, or by recursively applying the bucket sorting algorithm.
5+
* @complexity_analysis
6+
* Space Complexity - O(n + k)
7+
* Time Complexity - O(n + k)
8+
* @param {number[]} arr - The array to be sorted.
9+
* @returns {number[]} - The sorted array.
10+
* @see https://en.wikipedia.org/wiki/Bucket_sort
11+
* @example bucketSort([5, 4, 3, 2, 1]) // [1, 2, 3, 4, 5]
12+
*/
13+
14+
import { insertionSort } from "./insertion_sort";
15+
16+
export function bucketSort(arr: number[]): number[] {
17+
const buckets: number[][] = [];
18+
const sortedArray: number[] = [];
19+
20+
for (let i = 0; i < arr.length; i++) {
21+
const bucketIndex = Math.floor(arr[i] / 10);
22+
if (buckets[bucketIndex]) {
23+
buckets[bucketIndex].push(arr[i]);
24+
} else {
25+
buckets[bucketIndex] = [arr[i]];
26+
}
27+
}
28+
29+
for (let i = 0; i < buckets.length; i++) {
30+
if (buckets[i]) {
31+
insertionSort(buckets[i]);
32+
sortedArray.push(...buckets[i]);
33+
}
34+
}
35+
36+
return sortedArray;
37+
}

sorts/test/bucket_sort.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { bucketSort } from "../bucket_sort";
2+
3+
describe("Testing Bucket sort", () => {
4+
const testCases: number[][] = [];
5+
6+
for (let i = 0; i < 10; i++) {
7+
const arr = [];
8+
for (let j = 0; j < 100; j++) {
9+
arr.push(Math.floor(Math.random() * 100));
10+
}
11+
testCases.push(arr);
12+
}
13+
test.each(testCases)(
14+
"should return the correct value for test case: %#",
15+
(...arr: number[]) => {
16+
expect(bucketSort([...arr])).toStrictEqual(
17+
[...arr].sort((a: number, b: number) => a - b)
18+
);
19+
}
20+
);
21+
});

0 commit comments

Comments
 (0)