桶排序就是将待排数组的元素按某种函数关系分成若干组,将每组的元素分别丢进桶里,把每个桶里的元素都排序,然后再按顺序取出组成一个有序数组。
*注:图片来自《算法导论》
用链表实现:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node{
int e;
struct node* next;
}Node;
int bksort(int* arr,int sz,int n,int m)//n为桶个数,m为整数的位数
{
int i,j,k,pos;
Node* p;
Node** bucket = (Node**)malloc(n*sizeof(Node*));
if(bucket == NULL) return 0;
for(i=0; i<n; i++)//初始化桶,e记录桶中元素的个数
{
bucket[i] = (Node*)malloc(sizeof(Node));
bucket[i]->e = 0;
bucket[i]->next = NULL;
}
for(i=0; i<sz; i++)
{
Node* node = (Node*)malloc(sizeof(Node));
node->e= arr[i];
node->next = NULL;
k = arr[i]/((m-1)*10);
p = bucket[k];
if(p->next == NULL)
{
//往桶里放第一个元素
p->next = node;
p->e++;
}
else
{
//按小到大顺序往桶里扔元素
while(p->next!=NULL && p->next->e <= node->e)
p = p->next;
node->next = p->next;
p->next = node;
(bucket[k]->e)++;
}
}
pos = 0;
for(i=0; i<n; i++)//按顺序从桶里拿出元素放在原数组arr中
{
for(j=0; j<bucket[i]->e; j++)
{
arr[pos++] = bucket[i]->next->e;
if(bucket[i]->next->next !== NULL)
bucket[i]->next = bucket[i]->next->next;
}
}
free(bucket);
return 1;
}
int main()
{
int i = 0;
int arr[] = {78,17,39,26,72,94,21,12,23,68};
int sz = sizeof(arr)/sizeof(arr[0]);
bksort(arr,sz,10,2);
for(i=0; i<sz; i++)
printf("%d ",arr[i]);
return 0;
}
时间复杂度为O(n)。