Skip to content

Commit 38760ff

Browse files
committed
added PigeonHoleSort algorithm
1 parent e92b5d2 commit 38760ff

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Sorts/PigeonHoleSort.js

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

0 commit comments

Comments
 (0)