整数排序——基数排序

    看算法,看到用基数排序来对整数进行排序时,算法复杂度为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;
}
结果


这是有多快,吖。。。。。

转载于:https://my.oschina.net/u/1022744/blog/148790

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值