基数排序

来源:互联网 发布:淘宝客设置通用计划 编辑:程序博客网 时间:2024/06/05 04:09

基数排序详见《数据结构与算法分析》40页

//待排序vector中数的最大位数int maxbit(const vector<int>& unSort){    int maxb = 0;    for (int i = 0; i<unSort.size(); i++)    {        int tempMaxb = 1;        int tempNum = unSort[i];        while (tempNum / 10)        {            tempNum = tempNum / 10;            tempMaxb++;        }        if (tempMaxb>maxb)            maxb = tempMaxb;    }    return maxb;}//基数排序void radixSort(vector<int>& unSort){    vector<vector<int>> count;//桶    vector<vector<int>> tempCount;//临时桶    for (size_t i = 0; i < 10; i++)    {        vector<int> temp;        count.push_back(temp);    }    size_t maxBite = maxbit(unSort);    int base = 1;    //第一次桶排序    while (unSort.size() != 0)    {        count[(unSort.back() / base) % 10].push_back(unSort.back());        unSort.pop_back();    }    //主循环    for (size_t t = 0; t < maxBite; t++)    {        tempCount.clear();        tempCount = count;        for (size_t i = 0; i < 10; i++)        {            count[i].clear();//清理桶        }        base = base * 10;        for (size_t i = 0; i < 10; i++)        {            for (size_t j = 0; j < tempCount[i].size(); j++)            {                count[(tempCount[i][j] / base) % 10].push_back(tempCount[i][j]);            }        }    }    unSort = count[0];}