数据结构—基数排序

#include

#include    //STL链表

 

using namespace std;

 

int maxdigit(int data[], int n)        //判断最大的数的位数

{

    int d = 1;

    int p = 10;

    for (int i = 0; i < n; i++)

    {

        while (data[i] > p)

        {

            p *= 10;

            ++d;

        }

    }

    return d;

}

 

void radixsort(int data[], int n)    //基数排序

{

    int digits = maxdigit(data, n);

    list lists[10];

    int d, j, k, factor;

    for (d = 1, factor = 1; d <= digits; factor *= 10, d++)

    {

        for (j = 0; j < n; j++)

        {

            lists[(data[j] / factor) % 10].push_back(data[j]);        //提取每个数的个位,十位,百位等...

        }

        for (j = k = 0; j < 10; j++)

        {

            while (!lists[j].empty())

            {

                data[k++] = lists[j].front();

                lists[j].pop_front();

            }

        }

    }

 

}

 

int main()

{

    int data[10] = { 179, 208, 306, 93, 859, 984, 55, 9, 271, 33 };

    cout << "排序前:" << endl;

    for (int i = 0; i < 10; i++)

        cout << data[i] << " ";

    cout << endl;

    radixsort(data, 10);    //基数排序

    cout << "排序后:" << endl;

    for (int i = 0; i < 10; i++)

        cout << data[i] << " ";

    cout << endl;

    system("pause");

    return 0;

}

运行结果:

数据结构—基数排序

posted @ 2016-04-30 15:51  硫酸亚铜  阅读(224)  评论(0编辑  收藏  举报