bucket sort

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".

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值