Pigeon Nest Sorting algorithm description and code example

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.