基数排序
实现原理:将所有待比较数值(正整数)统一为同样的数位长度,数位较短的数前面补零。然后,从最低位开始,依次进行一次排序。
这样从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列。
实验数据:
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;
}
结果: