基数排序

基数排序

实现原理:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。
这样从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列。

实验数据:

138,47, 65, 97, 13, 27, 49,76

 第一次1.将数据分到1-9中


2得到结果 其中 newtemp[i+1] = newtemp[i] +temp[i] i为下标  newtemp记录更新时数据插入的位置

3.对数据进行更新:

第二次  步骤如上

   




第三次

   




代码:

# include <stdio.h> 
# include <math.h>
# include <stdlib.h>
//本次基数排序采取最低位优先即LSD法 
int MaxLength(int *a, int n){
	//用于计算数组a中最大的元素是几位数 
	int length = 1, i;
	for(i = 0; i < n; i++){
		while(a[i]/(int)pow(10, length)){
			length++;
		}
	}	
	return length;
}

void GetTempCount(int *a, int n, int count, int*temp){
	int num;
	int i;
	for(i = 0; i < 10; i++){
		temp[i] = 0;
	} 
	for(i = 0; i < n; i++){
		num = a[i]/(int)pow(10, count-1);
		temp[num%10]++;
	}
	
	return ;
}

void Updata(int *a, int n, int count,int *temp){
	 //此函数用于更新数组a中的数据 
	 int newtemp[11]={0}, num;
	 int *b = (int *)malloc(sizeof(int)*(n+1)); 
	 for(int i = 0; i < 10; i++){
	 	newtemp[i+1] = newtemp[i]+temp[i]; 
	 } 
	 for(int i = n-1; i>= 0; i--){
	 	num =(a[i]/(int)pow(10, count-1))%10;
		b[newtemp[num+1]]= a[i];
		newtemp[num+1]--; 
	 }
	 for(int i = 0; i < n; i++){
	 	a[i] = b[i+1];
	 }
	 return ;
}

void BinSort(int *a, int n){
	int length, i = 1, j;
	
	int temp[10]={0}; 
	length = MaxLength(a , n);
	while(i<=length){
		GetTempCount(a, n, i, temp);
		Updata(a, n, i, temp); 
		for(j = 0; j < n; j++){
			printf("%d ", a[j]);
		}
		printf("\n");
		i++;	
	} 
	return ;
}
	
int main(void){
	int a[] = { 138,47, 65, 97, 13, 27, 49,76 };
	BinSort(a, 8);
	return 0;
}
结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值