Bucket sort runs in linear time when the input is drawn from a uniform distribution. Bucket sort assumes that the input is generated by a random process that distributes elements uniformly over the interval[0, 1).
The algorithm is :
(Our code for bucket sort assumes that the input is an n-element array A and that each element A[i] in the array satisfies 0<=A[i]<1). The code requires an auxiliary array B[0...n-1] of linked lists(buckets) and assumes that there is a mechanism for maintaining such list.
BUCKET-SORT(A)
n<--length[A]
for i<--1 to n
do insert A[i] into list B[nA[i]] // nA[i] lower limit
for i<--0 to n-1
do sort list B[i] with insertion sort
concatenate the lists B[0], B[1], ..., B[n-1] together in order.
#include <stdio.h>
#include <malloc.h>
typedef struct Node
{
float data;
struct Node *next;
}Node, *PNode;
// A array has n elements
void bucket_sort(float A[], int n)
{
PNode *B = (PNode *)malloc(sizeof(PNode)*n), p, q;
int i, index;
for (i=0; i<n; i++)
{
B[i] = NULL;
}
for (i=0; i<n; i++)
{
index = (int)(n*A[i]);
p = B[index];
q = (PNode)malloc(sizeof(Node));
q->data = A[i];
if (p == NULL)
{
B[index] = q;
q->next = NULL;
}
else // insert the data to proper position
{
PNode r;
r = p;
// find position
while (r && (r->data-A[i] < 1e-6))
{
p = r;
r = r->next;
}
// in the middle
if (r!=B[index])
{
q->next = r;
p->next = q;
}
else // in the head
{
q->next = p;
B[index] = q;
}
}
}
// output the elements
for (i=0; i<n; i++)
{
p = B[i];
while (p)
{
printf("%f\t", p->data);
p = p->next;
}
}
printf("\n");
// free the space
for (i=0; i<n; i++)
{
PNode q;
p = B[i];
while (p)
{
q = p;
p = p->next;
free(q);
}
}
free(B);
}
int main()
{
float A[] = {.78, .17, .39, .26, .72, .94, .21, .12, .23, .68};
bucket_sort(A, 10);
return 0;
}
From "Introduction to algorithms".
1425

被折叠的 条评论
为什么被折叠?



