Radix / LSD排序队列c ++

时间:2016-05-28 10:19:17

标签: c++ algorithm sorting complexity-theory radix-sort

我自己使用队列写了基数排序,因为我们在课堂上理论上使用它并且它对我来说非常有趣。我熟悉算法并阅读关于基数排序的this article,然后是说明ylc

我通过使用伪随机数测试它,看起来它正在完成它的工作 - 数组在最后排序。我对正确的内存管理有些怀疑。正好删除表单队列并将其插入到数组中。

首先提出问题:内存是否泄漏?

我还考虑了这种算法的复杂性。我读了关于效率的this artticle

  

n - 数组的大小
   w - 我们最大号码中的职位数量    c1 =最大功能比较 - 完成 n 次    c2 =在队列中插入 - 完成 n * w 次    c3 =从队列中删除 - 已完成 n * w 次    c4 =在数组中插入 - 完成 n * w

     

T(n)= n c1 + n w *(c2 + c3 + c4)= O(w * n)

内存复杂度 T(n)= n * sizeof(节点)

严重问题:逻辑上这是推理吗?

基数排序

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

struct list
{
    int key;
    list *next;
};
//pointers to structure to do queue
list* ptr [10], *head[10];

//function that returns the maximum of the table
int maxi (int *t, int n)
{
    int max= t[0];
    for(int i = 1; i<n; i++)
    {
        if (t[i]>max)
        max = t[i];
    }
    return max;
}
//sort
void radx(int *t,int  n )
{
    list * tmp, *temp;  //the queue management
    int exp = 10;                       
    int k, j = 0 , l=1;
    int max = maxi(t,n);        


    for(int i=0; i=max*10/exp; i++)
    {   
    //insertion to queue
        for(int i =0 ; i<n; i++)
        {
            k = ((t[i]%exp)/l); //digit of our position 
            if(head[k] == NULL)
            {
                head[k] = new list;
                head[k]->key = t[i];
                head[k]->next = NULL;
            }
            else
            {
                tmp = head[k];
                tmp->next;
                while (tmp->next)
                {
                    tmp = tmp->next;
                }
                ptr[k] = new list;
                ptr[k] -> key = t[i];
                tmp->next = ptr[k];
                ptr[k]->next = NULL;
            }
        }
        //remove and writeback at table
        for(int i= 0; i<10; i++)
        {
            tmp = head[i];
            while(tmp)
            {   
                t[j] = tmp->key;
                temp = tmp;
                tmp = tmp->next;
                delete temp;
                j++;
            }
            head[i] = NULL;
        }

            exp *= 10;  //next position of number
            l   *= 10;
            j    = 0;
    }


}
void Random (int n, int a, int b, int *t)
{
    for (int i=0; i<n; i++)
    {
        t[i] =  rand()% (b-a+1)+a;  
    }
}
int main()
{   
    srand(time(0));
    int n, a, b;
    cout<<"How many elements: ";
    cin>>n;
    int *t = new int [n];
    cout<<endl<<"Range from to: ";
    cin>>a>>b;

    Random(n, a, b, t);

    radx(t, n);

    for(int i=0; i<n; i++)
    cout<<t[i]<<" ";


    delete []t;
return 0;
}

0 个答案:

没有答案
相关问题