排序 --- 基数排序(桶排序)

基数排序(桶排序)


 

  • 基本思想:

 

  • 时间复杂度与空间复杂度分析:

  • 基数排序分类:LSD+MSD

  • 1.LSD算法分析:

最低位优先法,简称LSD法:先从最低位开始排序,再对次低位排序,直到对最高位排序后得到一个有序序列。

 

  • 2.MSD算法分析:

  • 代码实现

  • 1.(LSD)

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

typedef struct Node
{
	int data;
	struct Node *next;
}Node,*List;

void InitList(List plist)
{
	assert(plist!=NULL);
	plist->next=NULL;
}

static Node *GetNode(int val)
{
	Node* pGet = (Node *)malloc(sizeof(Node));
	assert(pGet != NULL);
	pGet->data = val;
	pGet->next = NULL;
	return pGet;
}



bool Insert_tail(List plist,int val)//尾插法
{
	Node *cur = plist;//指向头结点  依赖前驱信息的
	while(cur->next != NULL)
	{
		cur = cur->next;
	}
	Node *pGet = GetNode(val);
	cur->next = pGet;
	return true;
}

bool Delete_first(List plist,int *rtv)
{
	List pDel=plist->next;
	if(pDel==NULL)
	{
		return false;
	}
	*rtv=pDel->data;
	plist->next=pDel->next;
	free(pDel);
	pDel=NULL;
	return true;
}


void Show(int *arr,int len)
{
	assert(arr!=NULL&&len>0);
	for(int i=0;i<len;i++)
	{
		printf("%d  ",arr[i]);
	}
	printf("\n");
}


int GetMaxBit(int *arr,int len)
{
	assert(arr!=NULL&&len>0);
	int Max=arr[0];
	int count=0;
	for(int i=1;i<len;i++)
	{
		if(arr[i]>Max){Max=arr[i];}
	}
	while(Max!=0)
	{
		Max/=10;
		count++;
	}
	return count;
	
}

int GetNum(int num,int figures)
{
	int temp=0;
	while (figures--)
	{
		temp=num%10;
		num/=10;
	}
	return temp;
}

void Radix(int *arr,int len,int figures )//figures 从右往左的第figures位
{
	assert(arr!=NULL&&len>0);
	Node head[10];//
	int i=0;
	for(i=0 ;i<10;i++)
	{
		InitList(&head[i]);
	}
	//1.入桶--》拿数字,判断figures位,入相应的桶

	int tmp=0;
	for(i=0;i<len;i++)
	{
		tmp=GetNum(arr[i],figures);
		Insert_tail(&head[tmp],arr[i]);	
	}

	//2.出桶
	i=0;
	for(int j =0;j<10;j++)//j代表桶的个数
	{
		int temp;
		while(Delete_first(&head[j],&temp))
		{
			arr[i++]=temp;
		}
		
	}

}

//基数排序    时间复杂度 O(d*n)
void Radix_Sort(int *arr,int len)
{
	int count=GetMaxBit(arr,len);
	for(int i=1;i<=count;i++)
	{
		Radix(arr,len,i);//i  
	}
}


int main()
{
	int arr[]={1,33,4534,343,232,12,3232,12,12,12,12,12,12,,13,1,23,124,32,4,235};
	int len=sizeof(arr)/sizeof(arr[0]);
	Radix_Sort(arr,len);
	Show(arr,len);
	system("pause");
	return 0;
}
  • 2.  (MSD)

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值