Skip to content

Commit db5510d

Browse files
dev-madhurendramadhuredraappgurueu
authored
feat : added counting sort method (#170)
* feat : added counting sort method * Remove some unnecessary colons --------- Co-authored-by: madhuredra <madhuredra.tiwari@zemosolabs.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
1 parent 269cfc8 commit db5510d

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

sorts/counting_sort.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @author dev-madhurendra
3+
* Counting sort is an algorithm for sorting a collection
4+
* of objects according to keys that are small integers.
5+
* @see https://en.wikipedia.org/wiki/Counting_sort
6+
* @example
7+
* const array = [3, 0, 2, 5, 4, 1]
8+
* countingSort(array, 0, 5)
9+
*/
10+
11+
export const countingSort = (inputArr: number[], min: number, max: number) => {
12+
const sortedArr = []
13+
14+
const count = new Array(max - min + 1).fill(0)
15+
16+
for (let i = 0; i < inputArr.length; i++)
17+
count[inputArr[i] - min]++
18+
19+
count[0] -= 1
20+
21+
for (let i = 1; i < count.length; i++)
22+
count[i] += count[i - 1]
23+
24+
for (let i = inputArr.length - 1; i >= 0; i--) {
25+
sortedArr[count[inputArr[i] - min]] = inputArr[i]
26+
count[inputArr[i] - min]--
27+
}
28+
29+
return sortedArr
30+
}

sorts/test/counting_sort.test.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { countingSort } from "../counting_sort";
2+
3+
const testCases = [
4+
[
5+
[3, 0, 2, 5, 4, 1],
6+
[0, 1, 2, 3, 4, 5],
7+
],
8+
[
9+
[6, 4, 2, 1, 3, 5],
10+
[1, 2, 3, 4, 5, 6],
11+
],
12+
[
13+
[11, 14, 12, 15, 16, 13],
14+
[11, 12, 13, 14, 15, 16],
15+
],
16+
[
17+
[13, 18, 2, 15, 43, 11],
18+
[2, 11, 13, 15, 18, 43],
19+
],
20+
];
21+
22+
it.each(testCases)(
23+
'The countingSort of the array %p is %p',
24+
(input, expected) => {
25+
const res = countingSort(input, Math.min(...input), Math.max(...input));
26+
expect(res).toEqual(expected);
27+
}
28+
);

0 commit comments

Comments
 (0)