桶排序 + 基数排序

  C++实现的“桶排序”,采用了模板技术。底层数据结构是 std::map ,其本质是优先队列。

  时间复杂度是O(M + N),其中 M 是数据范围的最大值,N 是数据量。额外的,当 M = O(N) 时,时间复杂度是 O(N)。

#include <iostream>
#include <map>

using namespace std;

template<typename T>
void bucketSorting(T* begin, T* end)
{
    T* it = begin;
    
    map<T, unsigned> bucket;

    while (it != end)
        bucket[*it++]++;

    for (auto e : bucket)
        *begin++ = e.first;
}

int main()
{
    int arr[] = { 5, 4, 30, 10, 100 };

    bucketSorting(arr, (arr + 5));

    for (auto e : arr)
        cout << e << " ";

    return 0;
}

   

  基于“多趟桶排序”的基数排序

  《数据结构与算法分析——C 语言描述》 P40 基数排序,利用 C++ 模板、仿照 STL sort 函数实现。

#include <iostream>
#include <vector>

using namespace std;

template<typename T>
void RedixSort(T *first, T *last, const unsigned int maxLongth)
{
    vector<T> buckets[10];

    for (T *it = first; it != last; it++)
        (buckets[getFigure(*it, 0)]).push_back(*it);

    for (unsigned i = 1; i < maxLongth; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            for (size_t size = (buckets[j]).size(); size > 0; size--)
            {
                int figure = getFigure((buckets[j])[size - 1], i);
                (buckets[figure]).push_back((buckets[j])[size - 1]);
                (buckets[j]).pop_back();
            }
        }
    }

    for (auto e : buckets)
        for (auto e2 : e)
            *first++ = e2;
}

unsigned int getFigure(int number, const unsigned int n)
{
    for (unsigned int i = 0; i < n; i++)
        number /= 10;

    return number % 10;
}

int main()
{
    int arr[] = { 4321, 321, 21, 1, 0 };

    RedixSort(arr, arr + 5, 4);

    for (auto e : arr)
        cout << e << " ";

    return 0;
}
View Code