排序(六)非比较排序
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; } }