【C++代码】之《桶排序》

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

template <typename type>
void BucketSort(vector<type> & array)
{
    const int length = array.size();
    if (length <= 1)
    {
        return ;
    }
    else
    {
        // 找到最大最小值
        const type max = *max_element(array.begin(), array.end());
        const type min = *min_element(array.begin(), array.end());
        // 初始化bucket
        const int bucketNum = length;
        const type range = (max - min) / (bucketNum - 1);
        vector<vector<type>> tempArray(bucketNum);
        // 将元素放入桶中
        for (int i = 0; i < length; ++i)
        {
            int num = static_cast<int>((array[i] - min) / range);
            tempArray[num].push_back(array[i]);
        }
        // 桶的内部排序
        for (int i = 0; i < tempArray.size(); ++i)
        {
            sort(tempArray[i].begin(), tempArray[i].end());
        }
        // 输出全出元素
        array.clear();
        for (int i = 0; i < tempArray.size(); ++i)
        {
            for (int j = 0; j < tempArray[i].size(); ++j)
            {
                array.push_back(tempArray[i][j]);
            }
        }
    }
}


int main()
{
    vector<double> array = {4.5, 0.84, 3.25, 2.18, 0.5, 0.6, 10.1};
    BucketSort(array);
    for (int i = 0; i < array.size(); ++i)
    {
        cout << array[i] << '\t';
    }
    cout << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_27577651/article/details/107483619