基数排序

前言

当序列中元素范围比较大时,就不适合使用计数排序。针对这种情况,就有了基数排序(Radix Sort),这是一种按位排序。它仍然是以计数排序为基础。

基数排序

基数排序的基数:十进制数的基数自然是10,二进制的基数自然是2。通常有两种按位排序策略:1.高位优先法(most significant digit first,MSD):简单讲就是从高位排起。2.低位优先法(least significant digit first,LSD):它与高位优先相反,从低位排起。从排序效果上看,高位优先比较直观,但却涉及到递归的过程,故最常用的还是低位优先法。说它以计数排序为基础,理由如下,以最常见的十进制数为例:


仔细理解上图,高位优先的过程你也一定可以推测出来。下面给出低位优先下的代码。

代码

#include<iostream>
#include<iomanip>
using namespace std;
//获取最大位数
int get_max_digit(int array[], int n)
{
	int digit, max;
	digit = 0;
	max = array[0];
	for (int i = 1; i < n; i++)
	{
		if (array[i] > max)
			max = array[i];
	}
	while (max)
	{
		digit++;
		max /= 10;
	}
	return digit;
}
//基数排序
void RadixSort(int array[], int n)
{
	//创建临时数组
	int *temp = new int[n];
	//位数:决定了排序趟数
	int digit = get_max_digit(array, n);
	//计数数组
	int count[10];
	//排序
	int r, i, d;
	for (r = 1; r <= digit; r++)
	{
		//重置计数数组
		memset(count, 0, 10 * sizeof(int));
		//把数据存储到临时数组
		memcpy(temp, array, n*sizeof(int));
		d = i = 1;
		while (i < r)
		{
			i++;
			d *= 10;
		}
		for (i = 0; i < n; i++)
			count[(array[i] / d) % 10]++;
		for (i = 1; i < 10; i++)
			count[i] += count[i - 1];
		//数据回放
		for (i = n - 1; i >= 0; i--)
			array[--count[(temp[i] / d) % 10]] = temp[i];
	}
}
void print(int array[], int n)
{
	for (int i = 0; i < n; i++)
		cout << setw(6) << array[i];
	cout << endl;
}
int main()
{
	cout << "******基数排序***by David***" << endl;
	int array[] = { 123, 234, 45, 111, 6, 128 };
	int n = sizeof(array) / sizeof(int);
	cout << "原序列" << endl;
	print(array, n);
	cout << "基数排序" << endl;
	RadixSort(array, n);
	print(array, n);
	system("pause");
	return 0;
}

运行    



转载请注明出处,本文地址:http://blog.csdn.net/zhangxiangdavaid/article/details/37612595


若是有所帮助,顶一个哦!


专栏目录:



  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值