Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 1be2095

Browse files
authored
Add counting sort algorithm in JavaScript (#911)
1 parent 528075f commit 1be2095

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const countingSort = (inputArr, n = inputArr.length) => {
2+
let k = Math.max(...inputArr);
3+
let t;
4+
const temp = new Array(k + 1).fill(0);
5+
6+
for(let i = 0; i < n; i++){
7+
t = inputArr[i];
8+
temp[t]++;
9+
}
10+
11+
for(let i = 1; i <= k; i++){
12+
13+
temp[i] = temp[i] + temp[i - 1];
14+
}
15+
16+
const outputArr = new Array(n).fill(0);
17+
18+
for(let i = n - 1; i >= 0; i--) {
19+
20+
t = inputArr[i];
21+
outputArr[temp[t] - 1] = t;
22+
23+
temp[t] = temp[t] - 1;
24+
}
25+
26+
return outputArr;
27+
}

0 commit comments

Comments
 (0)