Pigeon Nest Sort
Applicable conditions: The range of all values is determined, and the frequency of the occurrence of elements in this range is higher.
Algorithm Description: A one-dimensional array is used to nest the elements that may be taken within the range of values.
The number of occurrences of the element in the nest (by traversing the number of statistics to be sorted). According to the nest
Order and the number of elements in the nest lists the ordered sequence.
The spatial complexity of the algorithm is: S (1) Time complexity is: O (n).
Example: 20 non-negative numbers, where the value range for each number is 1~9.
#include <iostream>
#include <time.h>
using namespace Std;
int Myrand (int* src, int n)//random function, randomly generates n 0~9 number in src array
{
if (NULL = = src| | N < 0)
{
cout << "err in args or ' n '" << Endl;
return 0;
}
Else
{
Srand (Time (NULL));
for (int i=0; i<n; i++)
{
Src[i] = rand ()%10;
}
return 1;
}
}
void Prin (const int* src, int n)//first n elements in the output array
{
for (int i=0; i<n; i++)
cout << Src[i] << "";
cout << Endl;
}
void Home_sort (int arg[], int ar, int ser[], int se)//Sort function
{
int i,j,t = 0;
for (i=0; i<ar; i++)
++ser[arg[i]];
for (i=0; i<se; i++)
{
for (j=0; j<ser[i]; j + +)
{
Arg[t] = i;
++t;
}
}
}
int main ()
{
int arg[20],se[10] = {0};
if (Myrand (arg,20))
Prin (arg,20);
Home_sort (ARG, +, SE, 10);
Prin (ARG, 20);
return 0;
}
Pigeon Nest Sorting algorithm description and code example