forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPigeonHoleSort.js
More file actions
33 lines (27 loc) · 759 Bytes
/
PigeonHoleSort.js
File metadata and controls
33 lines (27 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
https://en.wikipedia.org/wiki/Pigeonhole_sort
*Pigeonhole sorting is a sorting algorithm that is suitable
* for sorting lists of elements where the number of elements
* (n) and the length of the range of possible key values (N)
* are approximately the same.
*/
export function pigeonHoleSort (arr) {
let min = arr[0]
let max = arr[0]
for (let i = 0; i < arr.length; i++) {
if (arr[i] > max) { max = arr[i] }
if (arr[i] < min) { min = arr[i] }
}
const range = max - min + 1
const pigeonhole = Array(range).fill(0)
for (let i = 0; i < arr.length; i++) {
pigeonhole[arr[i] - min]++
}
let index = 0
for (let j = 0; j < range; j++) {
while (pigeonhole[j]-- > 0) {
arr[index++] = j + min
}
}
return arr
}