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 2b95c9b

Browse files
add counting sort
1 parent 733e04e commit 2b95c9b

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

‎README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ Feel free to navigate around.
5555

5656
[Bubble sort](https://github.com/estevanmaito/algorithms-in-javascript/tree/master/sorting/bubble-sort.js)
5757

58+
[Counting sort](https://github.com/estevanmaito/algorithms-in-javascript/tree/master/sorting/counting-sort.js)
59+
5860
[Heap sort](https://github.com/estevanmaito/algorithms-in-javascript/tree/master/sorting/heap-sort.js)
5961

6062
[Insertion sort](https://github.com/estevanmaito/algorithms-in-javascript/tree/master/sorting/insertion-sort.js)

‎sorting/counting-sort.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Counting sort
2+
3+
let countingSort = (arr) => {
4+
let result = [],
5+
counting = [],
6+
maxArr = Math.max(...arr)
7+
8+
for (let i = 0; i <= maxArr; i++) {
9+
counting[i] = 0
10+
}
11+
12+
for (let j = 0; j < arr.length; j++) {
13+
counting[arr[j]] = counting[arr[j]] + 1
14+
}
15+
16+
for (let i = 1; i <= maxArr; i++) {
17+
counting[i] = counting[i] + counting[i - 1]
18+
}
19+
20+
for (let j = arr.length - 1; j >= 0; j--) {
21+
counting[arr[j]] = counting[arr[j]] - 1
22+
result[counting[arr[j]]] = arr[j]
23+
}
24+
25+
return result
26+
}
27+
28+
const test = require('tape')
29+
30+
test('Counting sort', assert => {
31+
assert.deepEqual(countingSort([2,5,3,0,2,3,0,3]), [0,0,2,2,3,3,3,5])
32+
assert.deepEqual(countingSort([2,4,6,5,1,3]), [1,2,3,4,5,6])
33+
assert.end()
34+
})

0 commit comments

Comments
(0)

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