forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPigeonholeSort.java
More file actions
54 lines (44 loc) · 1.44 KB
/
Copy pathPigeonholeSort.java
File metadata and controls
54 lines (44 loc) · 1.44 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.thealgorithms.sorts;
import java.util.*;
import static com.thealgorithms.sorts.SortUtils.*;
public class PigeonholeSort {
/*
This code implements the pigeonhole sort algorithm for the integer array,
but we can also implement this for string arrays too.
See https://www.geeksforgeeks.org/pigeonhole-sort/
*/
void sort(Integer[] array){
int maxElement = array[0];
for (int element: array) {
if (element > maxElement) maxElement = element;
}
int numOfPigeonholes = 1 + maxElement;
ArrayList<Integer>[] pigeonHole = new ArrayList[numOfPigeonholes];
for (int k=0; k<numOfPigeonholes; k++) {
pigeonHole[k] = new ArrayList<>();
}
for (int t: array) {
pigeonHole[t].add(t);
}
int k=0;
for (ArrayList<Integer> ph: pigeonHole) {
for (int elements: ph) {
array[k]=elements;
k=k+1;
}
}
}
public static void main(String[] args)
{
PigeonholeSort pigeonholeSort = new PigeonholeSort();
Integer[] arr = { 8, 3, 2, 7, 4, 6, 8 };
System.out.print("Unsorted order is : ");
print(arr);
pigeonholeSort.sort(arr);
System.out.print("Sorted order is : ");
for (int i = 0; i < arr.length; i++) {
assert (arr[i]) <= (arr[i+1]);
}
print(arr);
}
}