看算法,看到用基数排序来对整数进行排序时,算法复杂度为O(n)。赶脚好牛逼的样子,拿来和std::sort比比,不比不知道,一比吓一跳呀。上代码:
radix_sort.hpp
#include <algorithm>
template <typename T,const int r>
void radix_sort (T v[],const int begin,const int end)
{
unsigned const int lp = sizeof(T)/r;
unsigned const int step = r*8;
unsigned const long size = 1<<step;
unsigned const long mask = size -1;
unsigned int bucket[size];
T *temp = new T [end-begin];
if(!temp){
//error
return;
}
for(int i=0;i<lp;i++){
std::memset(bucket,0,size*sizeof(int));
for(int j=begin;j<end;++j){
++bucket[ (v[j]>>(i*step))&mask ];
temp[j]=v[j];
}
unsigned int pos = 0;
for(int j=0;j<size;++j){
unsigned int t = bucket[j];
bucket[j] = pos;
pos += t;
}
for(int j=begin;j<end;++j){
v[bucket[(temp[j]>>(i*step))&mask]++]=temp[j];
}
}
delete [] temp;
}
test.cpp
#include "radix_sort.h"
#include <iostream>
#include <boost/progress.hpp>
#include <cstdlib>
#include <ctime>
int main()
{
typedef int type;
const int N = 500000;
type *v=new type [N];
type *sv=new type [N];
int t=5;
for(int i=0;i<t;i++){
std::srand(time(0));
for(int j=0;j<N;j++)
v[j]=std::rand()%N;
std::memcpy(sv,v,N*sizeof(type));
{
std::cout<<"radix_sort\t:";
boost::progress_timer t;
radix_sort<type,1>(v,0,N);
}
{
std::cout<<"std::sort\t:";
boost::progress_timer t;
std::sort(sv,sv+N);
}
}
/*
for(int i=0;i<1000;i++){
std::cout<<v[i]<<","<<sv[i]<<" ";
}
*/
delete [] v;
delete [] sv;
}
结果
这是有多快,吖。。。。。