排序算法(三)

//8-bucket sort

void bucket_sort( int *arr, int n )

{

        vector< vector<int> >  buckets;

        int i;

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

        {

                vector<int> tmps;

                buckets.push_back( tmps );

        }

        int base;

        int *backup = new int[n];

        int *pos = new int[n];

        for( i=0; i<n; backup[i]=arr[i], pos[i]=i, ++i );

        base = 0;

        while( base<5 )

        {

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

                {

                        int idx=arr[pos[i]]%10;

                        buckets[idx].push_back(pos[i]);

                        arr[pos[i]] /= 10;

                }

                int j=0,k;

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

                {

                        for( k=0; k<buckets[i].size(); ++k )

                        {

                                pos[j++] = buckets[i][k];

                        }

                        buckets[i].clear();

                }

                ++base;

        }

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

        {

                arr[i] = backup[pos[i]];

        }

}

 

你可能感兴趣的:(排序算法)