码迷,mamicode.com
首页 > 编程语言 > 详细

基数排序(LSD)

时间:2015-08-10 00:23:20      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:基数排序

示例代码:

#include <iostream>
#include <cstdio>
using namespace std;
//基数排序(LSD)从最低位到最高位进行如此的分配收集
void print(int a[], int n)
{
	for(int t=0; t<n; ++t)
	{
		if(t+1<n)
		{
			printf("%d ", a[t]);
		} else {
			printf("%d\n", a[t]);
		}
	}
}

int caldigit(int num, int d)
{
	int a[3] = {1, 10, 100};
	return num/a[d]%10;
}
void radixSort(int a[], int begin, int end)
{
	int count[10];     //一共有10个桶
	int len = end-begin+1;
	int *p = (int*)malloc((end-begin+1)*sizeof(int));
	for(int i=0; i<3; ++i)   //一共有3位数字,从低位开始
	{
		for(int t=0; t<10; ++t)
		{
			count[t] = 0;
		}
		for(int t=begin; t<=end; ++t)
		{
			count[caldigit(a[t], i)]++;
		}
		for(int t=1; t<10; ++t)
		{
			count[t] += count[t-1];
		}
		for(int t=end; t>=begin; --t)      //从后往前排,保证基数排序的稳定性
		{
			int pos = caldigit(a[t], i);        //表示是第几号桶
			p[count[pos]-1] = a[t];
			count[pos]--;
		}
		for(int t=0; t<len; ++t)
		{
			a[t+begin] = p[t];
		}

	}
	free(p);
	return ;
}
int main()
{
	int a[] = {4, 2, 43, 29, 312, 412, 143, 689};
	printf("排序前:\n");
	print(a, 8);
	printf("排序后:\n");
	radixSort(a, 0, 7);
	print(a, 8);
	return 0;
}

运行结果:

技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

基数排序(LSD)

标签:基数排序

原文地址:http://blog.csdn.net/u012432475/article/details/47381665

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!