排序非比较排序
Posted Young_For_You
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了排序非比较排序相关的知识,希望对你有一定的参考价值。
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; } }
以上是关于排序非比较排序的主要内容,如果未能解决你的问题,请参考以下文章
超详细总结基于比较的七大经典 排序 -- 不会的童鞋快进来补习