Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d647668

Browse files
committed
implemented counting sort
1 parent 6ba1da2 commit d647668

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

‎src/sorting/counting.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const countingSort = (arr, min, max) => {
2+
// No need to sort the array if the array only has one element or empty
3+
if (arr.length < 2) return arr;
4+
5+
// Auxiliary array
6+
const counts = [];
7+
8+
for (let i = min; i <= max; i += 1) {
9+
counts[i] = 0;
10+
}
11+
12+
// increase index value
13+
arr.forEach((el) => { counts[el] += 1; });
14+
15+
const result = [];
16+
17+
// put everything in a new array
18+
for (let i = min; i <= max; i += 1) {
19+
while (counts[i] > 0) {
20+
result.push(i);
21+
counts[i] -= 1;
22+
}
23+
}
24+
25+
return result;
26+
};
27+
28+
module.exports = countingSort;

‎tests/sorting/counting.test.js‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const countingSort = require('../../src/sorting/counting');
2+
3+
describe('counting sort unit test:', () => {
4+
it('Test#1 simple', async () => {
5+
const want = [2, 3, 5, 6, 7, 9];
6+
const got = countingSort([5, 3, 7, 6, 2, 9], 2, 9);
7+
expect(got).toEqual(want);
8+
});
9+
10+
it('Test#2 duplicate value', async () => {
11+
const want = [2, 3, 5, 5, 6, 7, 7, 9];
12+
const got = countingSort([5, 3, 7, 6, 2, 9, 7, 5], 2, 9);
13+
expect(got).toEqual(want);
14+
});
15+
16+
it('Test#3 with negative value', async () => {
17+
const want = [-7, -7, -3, 6, 17, 34, 42, 50, 52, 83, 87, 89, 96];
18+
const got = countingSort([83, 52, 89, 42, 6, 87, 50, 17, 34, 96, -7, -3, -7], -7, 96);
19+
expect(got).toEqual(want);
20+
});
21+
});

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /