漫画算法笔记
桶排序
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <set>
#include <vector>
#include <iterator>
using namespace std;
vector<double> bucketSort(const vector<double>& vec)
{
double min, max;
auto minMax = std::minmax_element(vec.begin(), vec.end());
min = *minMax.first;
max = *minMax.second;
double d = max - min;
int bucketNum = vec.size();
vector<multiset<double>> bucketVec(bucketNum);
for ( int i = 0; i < vec.size(); ++i )
{
int num = static_cast<int>( (vec[i] - min) * (bucketNum - 1) / d );
bucketVec[num].insert(vec[i]);
}
vector<double> resVec(vec.size());
int index = 0;
for( auto &set : bucketVec )
{
for ( double val : set )
{
resVec[index++] = val;
}
}
return resVec;
}
int main(int argc, char** argv)
{
vector<double> vec = {4.12, 6.421, 0.0023, 3.0, 2.123, 8.122, 4.12, 10.09};
vec = bucketSort(vec);
std::copy(vec.begin(), vec.end(), std::ostream_iterator<double>(cout, " "));
cout << endl;
system("pause");
return 0;
}