桶排序
桶排序期望的运行时间是Θ(n)
局限:输入数组要在[0,1)之间(下面有更通用的版本3⃣️)
1⃣️内置排序没有用插入排序而是c++自带的sort,要用插入排序可保证算法稳定性。
void bucket_sort(float *array,int length){
vector<vector<float>> bucket(length);
for (int i = 0; i < length; ++i) {
bucket[(int)(length*array[i])].push_back(array[i]);
}
for (int i = 0; i < length; ++i) {
sort(bucket[i].begin(),bucket[i].end());
}
int index = 0;
for (int i = 0; i < length; ++i) {
while (bucket[i].size()>0)
{
array[index] = bucket[i][bucket[i].size()-1];
bucket[i].pop_back();
index++;
}
}
}
2⃣️对半径为1的圆周内不包含边界的点,对离圆心的距离进行排序
void bucket_sort(vector<Vector2>& array)
{
vector<vector<Vector2>> buckets(array.size());
for (int i = 0; i < array.size(); ++i) {
buckets[(int)(array[i].module()*array.size())].push_back(array[i]);
}
for (int i = 0; i < array.size(); ++i) {
sort(buckets[i].begin(),buckets[i].end(), compare);
}
int index = 0;
for (int i = 0; i < array.size(); ++i) {
while (buckets[i].size()>0)
{
array[index] = buckets[i][buckets[i].size()-1];
buckets[i].pop_back();
index++;
}
}
}
辅助Vector2类
class Vector2 {
public:
float x;
float y;
public:
Vector2(float x = 0.0,float y = 0.0);
float module() const;
};
static bool compare(const Vector2 &item1,const Vector2 &item2)
{
return item1.module() <= item2.module();
}
#include "Vector2.h"
Vector2::Vector2(float x,float y):x(x),y(y){}
float Vector2::module() const{
return sqrt(x*x+y*y);
}
3⃣️对变长整数的排序
算法导论第三版8-3a题,变长数据项的排序
void bucket_sort_variable_length(int *array,int length)
{
vector<vector<int>> positive_bucket(length);
vector<vector<int>> negative_bucket(length);
for (int i = 0; i < length; ++i) {
int len = get_int_length(array[i]);
if(array[i]<0)
{
negative_bucket[len-1].push_back(array[i]);
}
else
{
positive_bucket[len-1].push_back(array[i]);
}
}
for (int i = 0; i < length -1; ++i) {
if(negative_bucket[i].size()>0)
{
radix_sort(negative_bucket[i],i+1);
}
if(positive_bucket[i].size()>0)
{
radix_sort(positive_bucket[i],i+1);
}
}
int index = 0;
for (int i = length -1; i >= 0; --i) {
if(negative_bucket[i].size()>0)
{
copy(negative_bucket[i].begin(),negative_bucket[i].end(),array+index);
index += negative_bucket[i].size();
}
}
for (int i = 0; i < length -1; ++i) {
if(positive_bucket[i].size()>0)
{
copy(positive_bucket[i].begin(),positive_bucket[i].end(),array+index);
index += positive_bucket[i].size();
}
}
}
辅助函数 get_int_length
int get_int_length(int value)
{
int length = 0;
while (value != 0)
{
value /=10;
length++;
}
return length == 0 ? 1 : length;
}
4⃣️对变长字符串数组的的排序
算法导论第三版8-3b题,变长数据项的排序
void bucket_sort(vector<string>& array){
vector<vector<string>> bucket(26);
for (int i = 0; i < array.size(); ++i) {
bucket[tolower(array[i][0])-'a'].push_back(array[i]);
}
sort(bucket.begin(),bucket.end());
int index = 0;
for (int i = 0; i < 26; ++i) {
while (bucket[i].size()>0)
{
array[index] = bucket[i][0];
bucket[i].erase(bucket[i].begin());
index++;
}
}
}