排序算法(三)

//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]];
        }
}

 

posted @ 2014-03-18 12:54  samu  阅读(135)  评论(0编辑  收藏  举报