码迷,mamicode.com
首页 > 编程语言 > 详细

排序(六)非比较排序

时间:2016-06-16 13:06:58      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

1.计数排序

void CountSort(vector<int>& Vector)
    {
        int max = Vector[0], min = Vector[0];
        for (int i = 0; i < Vector.size(); ++i)
        {
            if (Vector[i]>max)
                max = Vector[i];
            else if (Vector[i] < min)
                min = Vector[i];
        }
        int size = max - min + 1;
        vector<int> tmp;
        tmp.resize(size);
        for (int i = 0; i < Vector.size(); ++i)    //利用新数组来记录数据,空间复杂度为O(N)
            tmp[Vector[i] - min]++;
        int index = 0;
        for (int i = 0; i < tmp.size(); ++i)
        while (tmp[i]--)
            Vector[index++] = min + i;
    }

 

2.基数排序

void BaseSort(vector<int>& Vector)
    {
        int MaxPosition = 1;
        int Data = 10;
        for (int i = 0; i < Vector.size(); ++i)
        {
            if (Vector[i] >= Data)
            {
                MaxPosition++;
                Data *= 10;
            }
        }

        vector<int> Count;    //计数数组
        vector<int> Start;    //计起始位置的数组
        vector<int> Zero;     //初始化数组
        Zero.resize(10);
        vector<int> Tmp;      //计排每一次的情况
        Tmp.resize(Vector.size());  
        Data = 1;
        for (int i = 0; i < MaxPosition; ++i)
        {
            Count = Zero;
            Start = Zero;

            for (int i = 0; i < Vector.size(); ++i)
                Count[Vector[i] / Data % 10]++;
            for (int i = 1; i < 10; ++i)
                Start[i] = Start[i - 1] + Count[i - 1];
            for (int i = 0; i < Vector.size(); ++i)
            {
                int index = Start[Vector[i] / Data % 10]++;
                Tmp[index] = Vector[i];
            }
            Vector = Tmp;
            Data *= 10;
        }
    }

 

排序(六)非比较排序

标签:

原文地址:http://www.cnblogs.com/shihaochangeworld/p/5590583.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!