C++ Program for Pigeonhole Sort?

C++Server Side ProgrammingProgramming

Pigeonhole Sort is an example of the non-comparison sorting technique. It is used where the number of items and the range of possible key values is approximately the same.

To perform this sort, we need to make some holes. The number of holes needed is decided by the range of numbers. In each hole, items are inserted. Finally deleted from the hole and stored into an array for sorted order.

Pigeonhole sorting, also known as count sort, is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the number of possible key values (N) are approximately the same.[1] It requires O(n + N) time.

Input: arr[]={7,4,2,6,3,1,5}
Output: 1 2 3 4 5 6 7

Explanation

  • Find minimum and maximum element in array. minimum and maximum elements will be ‘min’ and ‘max’ respectively. then find range as ‘max-min-1’.

  • Set up an array initially empty for “pigeonholes” the same size as of the range.

  • Traverse each element of the array and then put each element in its pigeonhole. An element arr[i] will be put in hole at index arr[i] – min.

  • The loop will start all over the pigeonhole array in order and put all of the elements from non- empty holes back into the original array.

Example

#include <iostream>
using namespace std;
#define MAX 7
void pigeonhole_sort(int, int, int *);
int main() {
   int i, min, max;
   int a[]={7,4,2,6,3,1,5};
   min = a[0];
   max = a[0];
   for (i = 1; i < MAX; i++) {
      if (a[i] < min) {
         min = a[i];
      }
      if (a[i] > max) {
         max = a[i];
      }
   }
   pigeonhole_sort(min, max, a);
   for (i = 0; i < MAX; i++) {
      cout<< a[i]<<"\t";
   }
}
void pigeonhole_sort(int mi, int ma, int * a) {
   int size, count = 0, i;
   int *current;
   current = a;
   size = ma - mi + 1;
   int holes[size];
   for (i = 0; i < size; i++) {
      holes[i] = 0;
   }
   for (i = 0; i < size; i++, current++) {
      holes[*current-mi] += 1;
   }
   for (count = 0, current = &a[0]; count < size; count++) {
      while (holes[count]--> 0) {
         *current++ = count + mi;
      }
   }
}

Output

1 2 3 4 5 6 7
raja
Published on 19-Aug-2019 07:58:11
Advertisements