C++实现基数排序

x33g5p2x  于2021-09-24 转载在 C/C++  
字(0.7k)|赞(0)|评价(0)|浏览(263)

#include<iostream>
#include<string.h>
#include<cmath>
using namespace std;
#define MaxSize 100

void RadixSort(int arry[], int size) //对三位数的整形数进行基数排序,size为数组大小 
{
	int temp[10][MaxSize];  //设置10个箱子,分别表示数字 0~9,每个箱子最多装 MaxSize个数据
	int count[10];          //记录每个箱子中的数据个数 
	memset(temp, 0, sizeof(temp)); //全部初始化为零 
	memset(count, 0, sizeof(count));
	
	for(int i=0; i<3; ++i)  //根据个位、十位、百位分别分配和收集一次,一共三次 
	{
		for(int j=0; j<size; ++j)  //分配 
		{
			int p = int(arry[j]/pow(10,i))%10;
			temp[p][count[p]] = arry[j];
			count[p]++;
		}
		int m = 0;
		for(int j=9; j>=0; --j)  //收集 
		{
			for(int q=0; q<count[j]; ++q)
			{
				arry[m] = temp[j][q];  
				m++;
			}
			count[j] = 0;  //箱子中的数据收集完后清零 
		}
	}
}

int main()
{
	int a[] = {81,94,11,96,12,35,17,95,28,58,41,75,15};
	RadixSort(a,13);
	for(int i=0; i<13; ++i)
	{
		cout << a[i] << " ";
	}
}

相关文章

微信公众号

最新文章

更多