简体   繁体   English

如何在 C++ 的计数排序算法中用随机数填充数组

[英]How to fill array with random numbers in Counting Sort Algorithm in C++

#include iostream

using namespace std;

int k=0;    

void sort_func(int A[],int B[],int n)    
{
    int count[k+1],t;
    for(int i=0;i<=k;i++)
    {
        count[i] = 0;
    }
    for(int i=0;i<n;i++)
    {
        t = A[i];
        count[t]++;         
    }
    for(int i=1;i<=k;i++)
    {
        count[i] = count[i]+count[i-1];            
    }
    for(int i=0;i<n;i++)
    {
        t = A[i];
        B[count[t]] = t;          
        count[t]=count[t]-1;        
    }
}

int main()
{
    int n;
    cout<<"Enter the size of the array :";
    cin>>n;
    int A[n],B[n]; 
    cout<<"Enter the array elements: ";
    for(int i=0;i<n;i++)        
    {
        cin>>A[i];
        if(A[i]>k)
        {
            k = A[i];              
        }
    }
    sort_func(A,B,n);        
    for(int i=1;i<=n;i++)       
    {
        cout<<B[i]<<" ";
    }
    cout<<"\n";
    return 0;
}

This is the C++ code for Counting Sort Algorithm and i can not change the code to create random array without entering values one by one edit:Yes i meant to create random values in array A by using rand() function.这是计数排序算法的 C++ 代码,如果不逐一输入值,我无法更改代码以创建随机数组

You could use the utilities from the <random> header:您可以使用<random> header 中的实用程序:

  • default_random_engine together with a random_device : for generating random numbers, and default_random_enginerandom_device一起:用于生成随机数,以及
  • uniform_int_distribution : for distributing those random numbers uniformly in a given range (in the example I use between 0 and 100 ). uniform_int_distribution :用于在给定范围内均匀分布这些随机数(在示例中我使用0100之间)。
    std::cout << "Filling array with random elements:\n\t";
    std::default_random_engine random_engine{ std::random_device{}() };
    std::uniform_int_distribution<int> uniform_dist{0, 100};
    std::for_each(A, A + n, [&uniform_dist, &random_engine](int& n) {
        n = uniform_dist(random_engine);
    });
    for (auto&& i : A) { std::cout << i << " "; }

You could also use max_element to calculate k .您还可以使用max_element来计算k

    k = *std::max_element(A, A + n);

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM