Skip to content

Commit 339e210

Browse files
authored
Merge pull request TheAlgorithms#547 from criskolonas/master
Added pigeonhole sorting
2 parents 91397ed + 2f5504e commit 339e210

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Sorts/PigeonHoleSort.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
https://en.wikipedia.org/wiki/Pigeonhole_sort
3+
4+
*Pigeonhole sorting is a sorting algorithm that is suitable
5+
* for sorting lists of elements where the number of elements
6+
* (n) and the length of the range of possible key values (N)
7+
* are approximately the same.
8+
*/
9+
function pigeonHoleSort (arr) {
10+
let min = arr[0]
11+
let max = arr[0]
12+
13+
for (let i = 0; i < arr.length; i++) {
14+
if (arr[i] > max) { max = arr[i] }
15+
if (arr[i] < min) { min = arr[i] }
16+
}
17+
console.log(max)
18+
console.log(min)
19+
20+
const range = max - min + 1
21+
const pigeonhole = Array(range).fill(0)
22+
23+
for (let i = 0; i < arr.length; i++) {
24+
pigeonhole[arr[i] - min]++
25+
}
26+
27+
let index = 0
28+
29+
for (let j = 0; j < range; j++) {
30+
while (pigeonhole[j]-- > 0) {
31+
arr[index++] = j + min
32+
}
33+
}
34+
}
35+
// Driver code
36+
const arr = [8, 3, 2, 7, 4, 6, 8]
37+
pigeonHoleSort(arr)
38+
console.log(arr)

0 commit comments

Comments
 (0)