From 64f1e51df47fb613c19dd877dcca0ed54af8d0d8 Mon Sep 17 00:00:00 2001 From: Yadunandan Bhat <54680617+yadunandanbhat@users.noreply.github.com> Date: Thu, 21 Apr 2022 18:05:27 +0530 Subject: [PATCH] Add pigeonhole sort (fixes #2992) (#3013) --- .../thealgorithms/sorts/PigeonholeSort.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/main/java/com/thealgorithms/sorts/PigeonholeSort.java diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java new file mode 100644 index 00000000..5025b7f6 --- /dev/null +++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java @@ -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[] pigeonHole = new ArrayList[numOfPigeonholes]; + + for (int k=0; k(); + } + + for (int t: array) { + pigeonHole[t].add(t); + } + + int k=0; + for (ArrayList 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); + } +}