簡體   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;
}

這是計數排序算法的 C++ 代碼,如果不逐一輸入值,我無法更改代碼以創建隨機數組

您可以使用<random> header 中的實用程序:

  • default_random_enginerandom_device一起:用於生成隨機數,以及
  • 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 << " "; }

您還可以使用max_element來計算k

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

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM