Skip to content

Commit 64f1e51

Browse files
Add pigeonhole sort (fixes TheAlgorithms#2992) (TheAlgorithms#3013)
1 parent 1320748 commit 64f1e51

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.thealgorithms.sorts;
2+
3+
import java.util.*;
4+
import static com.thealgorithms.sorts.SortUtils.*;
5+
6+
public class PigeonholeSort {
7+
/*
8+
This code implements the pigeonhole sort algorithm for the integer array,
9+
but we can also implement this for string arrays too.
10+
See https://www.geeksforgeeks.org/pigeonhole-sort/
11+
*/
12+
void sort(Integer[] array){
13+
int maxElement = array[0];
14+
for (int element: array) {
15+
if (element > maxElement) maxElement = element;
16+
}
17+
18+
int numOfPigeonholes = 1 + maxElement;
19+
ArrayList<Integer>[] pigeonHole = new ArrayList[numOfPigeonholes];
20+
21+
for (int k=0; k<numOfPigeonholes; k++) {
22+
pigeonHole[k] = new ArrayList<>();
23+
}
24+
25+
for (int t: array) {
26+
pigeonHole[t].add(t);
27+
}
28+
29+
int k=0;
30+
for (ArrayList<Integer> ph: pigeonHole) {
31+
for (int elements: ph) {
32+
array[k]=elements;
33+
k=k+1;
34+
}
35+
}
36+
}
37+
38+
public static void main(String[] args)
39+
{
40+
PigeonholeSort pigeonholeSort = new PigeonholeSort();
41+
Integer[] arr = { 8, 3, 2, 7, 4, 6, 8 };
42+
43+
System.out.print("Unsorted order is : ");
44+
print(arr);
45+
46+
pigeonholeSort.sort(arr);
47+
48+
System.out.print("Sorted order is : ");
49+
for (int i = 0; i < arr.length; i++) {
50+
assert (arr[i]) <= (arr[i+1]);
51+
}
52+
print(arr);
53+
}
54+
}

0 commit comments

Comments
 (0)