Add pigeonhole sort (fixes #2992) (#3013)

This commit is contained in:
Yadunandan Bhat 2022-04-21 18:05:27 +05:30 committed by GitHub
parent 1320748c88
commit 64f1e51df4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,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);
}
}