Java Program for Pigeonhole Sort


As the name suggests, pigeon holes are created, where the number of pigeon holes created is calculated using ‘max-min+1’, which is also known as the range of the array elements. The elements in the original array are iterated over and placed in the pigeonholes based on a specific condition.

Further, after all elements are put in the pigeonhole, they are put back into the array in the same order in which they were placed in the pigeon holes.

Example

Following is an example for Pigeonhole sort in Java −

 Live Demo

import java.lang.*;
import java.util.*;
public class Demo {
   public static void pigeonhole_sorting(int my_arr[], int n) {
      int min_element = my_arr[0];
      int max_element = my_arr[0];
      int my_range, i, j, index;
      for(int a=0; a<n; a++) {
         if(my_arr[a] > max_element)
            max_element = my_arr[a];
         if(my_arr[a] < min_element)
            min_element = my_arr[a];
      }
      my_range = max_element - min_element + 1;
      int[] sorted_arr = new int[my_range];
      Arrays.fill(sorted_arr, 0);
      for(i = 0; i<n; i++)
         sorted_arr[my_arr[i] - min_element]++;
         index = 0;
      for(j = 0; j<my_range; j++)
         while(sorted_arr[j]-->0)
         my_arr[index++]=j+min_element;
   }
   public static void main(String[] args) {
      Demo my_instance = new Demo();
      int[] my_arr = {45, 67, 1, 20, 99, 74, 78};
      System.out.print("The array, after performing pigeonhole sorting is : ");
      my_instance.pigeonhole_sorting(my_arr,my_arr.length);
      for(int i=0 ; i<my_arr.length ; i++)
      System.out.print(my_arr[i] + " ");
   }
}

Output

The array, after performing pigeonhole sorting is : 1 20 45 67 74 78 99

Explanation

Pigeonhole sort is usually used to sort list of elements, where number of elements and its associated key values are almost same. Its time complexity is O(n +range), where ‘n’ is the number of elements in the array and ‘range’ refers to the number of associated key values in the array.

First, the minimum and the maximum values of the array are found. These are assigned to two variables respectively. The range is found by calculating ‘max-min+1’.

An array with empty pigeonholes is set up, and the size of this array is same as that of the range. Every element in the array is iterated over, and every element is placed in the pigeonhole. This means if an element is in the original array in the position arr[i], in the pigeonhole, it is placed in ‘arr[i]-min_val’. Now, the pigeonhole array is iterated over and elements are put from populated holes back into the original array. This way, all the elements of the array would be sorted.

Updated on: 14-Sep-2020

298 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements