Skip to content

Commit 81bd46c

Browse files
committed
feat: add counting sort
Related: #14
1 parent 7153799 commit 81bd46c

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Sorts/countingSort.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
* Counting sort is an algorithm for sorting a collection of objects according to keys that are small integers;
3+
* that is, it is an integer sorting algorithm.
4+
* more information: https://en.wikipedia.org/wiki/Counting_sort
5+
* counting sort visualization: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html
6+
*/
7+
8+
function countingSort(arr, min, max) {
9+
let i;
10+
let z = 0;
11+
const count = [];
12+
13+
for (i = min; i <= max; i++) {
14+
count[i] = 0;
15+
}
16+
17+
for (i = 0; i < arr.length; i++) {
18+
count[arr[i]]++;
19+
}
20+
21+
for (i = min; i <= max; i++) {
22+
while (count[i]-- > 0) {
23+
arr[z++] = i;
24+
}
25+
}
26+
27+
return arr;
28+
}
29+
30+
const arr = [3, 0, 2, 5, 4, 1];
31+
32+
// Array before Sort
33+
console.log("-----before sorting-----");
34+
console.log(arr);
35+
// Array after sort
36+
console.log("-----after sorting-----");
37+
console.log(countingSort(arr, 0, 5));

0 commit comments

Comments
 (0)