基数排序的C实现

这是我第一次自己实现基数排序,我看了网上好多讲基数排序的都讲得乱起八糟,有的甚至给出来的代码还是错的。(附:我这个只当是一个启发式的代码。觉得博主有错的我请大家提出来,一起进步。感谢!!)


废话不多说,基数排序的定义自己百度。

我先来说说思路,基数排序是基于桶排序的一种线性排序方法,极其高效,如果一个需要排序的数组中最大元素小于1000大于100的话那么只需要执行两趟排序。

因为他是按照个、十、百位这样依次来进行排序的。先从最低位开始一直排到最高位

高效是这个算法的优点,但是占用的空间之多又是这个算法的不足之处!

我下面的这段代码克服了负数进行排序的问题,我看了网上许多人的代码对负数的排序是不支持的。我对负数进行排序的主要思路是这样:


设置长度为20的第一维

        1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19   

   分别对应-9,-8,-7,……,9;

这个类似于数轴,那么我们就抛弃了0这个位置。因为没有必要。10的这个位置就已经代表0

主要思路是这样,还是那句话源代码之中毫无秘密!


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//2015年05月12日 01:35:35  测试成功!
#define Test             0
#define Test_1           0
#define Test_2 0
#define Test_3           0
#define Test_4 1


#if(Test_1 || Test_2 || Test_3)
#define Max             10
#else
#define Max             30
#endif










void
Print(int *a,char ch)
{
int i;
switch(ch)
{
case 'F':printf("_____排序前的数组内容______\n");
break;
case 'A':printf("_____排序后的数组内容______\n");
break;
}


for(i = 0; i < Max; i++)
printf("%d ",a[i]);
printf("\n");

return ;
}




void
Radix_swap(int *a,int len,int count)
{
int Radix[20][100] = {{0},{0}};
int i,j,value = 1;
int counter = 0;
int state = -1,k;




for(i = 0;i < count; i++)
{


for(j = 0;j < len; )
{

if( 0 == Radix[(a[j]/value) % 10 + 10 ][counter] )
{
#if Test
printf(" 第一个为空Radix[(a[%d]/value) % 10][%d] = %d,a[%d] = %d\n"
,(a[j]/value) % 10 + 10,counter,Radix[(a[j]/value) % 10 + 10][counter],j,a[j]);
#endif
Radix[(a[j]/value) % 10 + 10][counter] = a[j++];
counter = 0;


}
else
counter++;

}
counter = 0;
for(j = 1,k = 0;counter < len && j < 20 && k < 100;)  // 为了安全起见这里必须保证它不越界
{
state = -1;
if( Radix[j][k] != 0)
{
a[counter++] = Radix[j][k];
#if Test
printf("复制 a[%d] = %d,Radix[%d][%d] = %d\n",counter,a[counter],j,k,Radix[j][k]);
#endif
Radix[j][k++] = 0;
state = 1;
}


if( state == -1 && Radix[j][k] == 0 )
{
j++;
k = 0;
}
}

value *= 10;
counter=0;
}
}






int
main(void)
{
//设置要排序的数组
#if Test_1
int array[Max] = {66,45,17,10,83,49,94,69,74,6};
#endif


#if Test_2
int array[Max] = {66,45,17,10,-83,49,94,69,74,-6};
#endif

#if Test_3
int array[Max] = {-3,-1,-41,-21,-30,-24,-66,4,-20,-67};
#endif

#if Test_4
//30组数据
int array[Max] = {-3,-1,-41,-21,-30,-24,-66,4,-20,-67,66,45,17,10,-83,49,94,69,74,-6,66,45,17,10,83,49,94,69,74,6};
#endif

Print(array,'F');
Radix_swap(array,Max,2);
Print(array,'A');

return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值