Skip to content

Commit 5531625

Browse files
committed
Add CountingSort in Javscript
1 parent 1949d91 commit 5531625

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -2943,8 +2943,8 @@ In order to achieve greater coverage and encourage more people to contribute to
29432943
</a>
29442944
</td>
29452945
<td> <!-- JavaScript -->
2946-
<a href="./CONTRIBUTING.md">
2947-
<img align="center" height="25" src="./logos/github.svg" />
2946+
<a href="./src/javascript/CountingSort.js">
2947+
<img align="center" height="25" src="./logos/javascript.svg" />
29482948
</a>
29492949
</td>
29502950
<td> <!-- Swift -->

src/javascript/CountingSort.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
function countingSort(arr) {
2+
// Find the maximum element in the array to determine the range
3+
let max = Math.max(...arr);
4+
5+
// Create a count array to store the count of each element
6+
let count = new Array(max + 1).fill(0);
7+
8+
// Count the occurrences of each element in the input array
9+
for (let i = 0; i < arr.length; i++) {
10+
count[arr[i]]++;
11+
}
12+
13+
// Modify the count array to store the actual position of each element
14+
for (let i = 1; i <= max; i++) {
15+
count[i] += count[i - 1];
16+
}
17+
18+
// Create a new output array and store the elements in their sorted order
19+
let output = new Array(arr.length);
20+
for (let i = arr.length - 1; i >= 0; i--) {
21+
output[count[arr[i]] - 1] = arr[i];
22+
count[arr[i]]--;
23+
}
24+
25+
return output;
26+
}
27+
28+
const arr = [4, 2, 2, 8, 3, 3, 1];
29+
const sortedArr = countingSort(arr);
30+
console.log("Original array:", arr);
31+
console.log("Sorted array:", sortedArr);

0 commit comments

Comments
 (0)