一、算法描述
- 将数组划分为一个个的桶,桶的结构是链表,对桶内元素进行插入排序
二、桶排序代码
struct node
{
int data;
struct node *next;
};
// 对每个链表(桶)进行插入排序
void insert_node(struct node **bucket, int data)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
p->data = data;
p->next = NULL;
// 桶为空
if(*bucket == NULL)
{
*bucket = p;
}else
{
struct node *pre = NULL;
struct node *cur = *bucket;
while(cur != NULL && cur->data <= data)
{
pre = cur;
cur = cur->next;
}
// 对插入到第一个结点前的情况处理
if(pre == NULL)
{
*bucket = p;
p->next = cur;
}else
{
pre->next = p;
p->next = cur;
}
}
}
// k表示数据位数,3为表示取值范围[000-999]
void bucket_sort(int a[], int length, int k)
{
// 申请桶空间
struct node **b = (struct node **)calloc(10,sizeof(struct node *));
int i,j,m;
// 将待排数据记录分配到桶
for(i=0; i<length; i++)
{
// 获取对应10个桶的标识 0-9
m = a[i];
for(j=k; j>1; j--)
m = m/10;
// 分配到桶链表中
insert_node(&b[m],a[i]);
}
// 方便返回结果,复制到原数组a中
// 复制到数组a中
struct node *p;
for(i=0,j=0; i<10 && j<length; i++)
{
if(b[i] != NULL)
{
p = b[i];
// 遍历每个桶元素
while(p != NULL)
{
a[j] = p->data;
j++;
p = p->next;
}
}
}
// 释放存储空间
for(i=0; i<10; i++)
{
while(b[i] !=NULL)
{
p = b[i];
b[i] = p->next;
free(p);
}
}
free(b);
}
三、测试代码
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
// 对每个链表(桶)进行插入排序
void insert_node(struct node **bucket, int data)
{
struct node *p = (struct node *)malloc(sizeof(struct node));
p->data = data;
p->next = NULL;
// 桶为空
if(*bucket == NULL)
{
*bucket = p;
}else
{
struct node *pre = NULL;
struct node *cur = *bucket;
while(cur != NULL && cur->data <= data)
{
pre = cur;
cur = cur->next;
}
// 对插入到第一个结点前的情况处理
if(pre == NULL)
{
*bucket = p;
p->next = cur;
}else
{
pre->next = p;
p->next = cur;
}
}
}
// k表示数据位数,3为表示取值范围[000-999]
void bucket_sort(int a[], int length, int k)
{
// 申请桶空间
struct node **b = (struct node **)calloc(10,sizeof(struct node *));
int i,j,m;
// 将待排数据记录分配到桶
for(i=0; i<length; i++)
{
// 获取对应10个桶的标识 0-9
m = a[i];
for(j=k; j>1; j--)
m = m/10;
// 分配到桶链表中
insert_node(&b[m],a[i]);
}
// 方便返回结果,复制到原数组a中
// 复制到数组a中
struct node *p;
for(i=0,j=0; i<10 && j<length; i++)
{
if(b[i] != NULL)
{
p = b[i];
// 遍历每个桶元素
while(p != NULL)
{
a[j] = p->data;
j++;
p = p->next;
}
}
}
// 释放存储空间
for(i=0; i<10; i++)
{
while(b[i] !=NULL)
{
p = b[i];
b[i] = p->next;
free(p);
}
}
free(b);
}
int main()
{
int N,i;
printf("请输入需要排序的数的个数:\n");
scanf("%d",&N);
int a[N];
printf("请输入需要排序的数:\n");
for(i=0;i<N;i++)
scanf("%d",&a[i]);
bucket_sort(a,N,3);
printf("桶排序的结果:\n");
for(i=0;i<N;i++)
printf("%d ",a[i]);
}
