排序算法之桶排序

View Code
  1 #include <stdio.h>
2 #include <stdlib.h>
3
4 #define N 10/*0-1分成10份,也即是说10个桶*/
5
6 /** AUTHOR: Mike Feng
7 * 桶排序:桶排序假设输入由一个随机过程产生,该过程将元素均匀而独立地分布在区间[0,1)上;
8 * 桶排序的思想就是把区间[0,1)划分成n个相同大小的子区间,或称为桶。然后,将n个输入数分布到各个桶中去;
9 * 为得到结果,先对各个桶中的数进行排序,然后按次序把各个桶中的元素列出来即可
10 */
11 struct node
12 {
13 double data;
14 struct node *next;
15 };
16
17 struct node **b; /*10个桶,用于装入0~1之间的数,没0.1段一个桶*/
18
19 /*打印a*/
20 void print(double *a)
21 {
22 int i;
23 for(i=0;i<N;i++)
24 printf("%lf\t",a[i]);
25 printf("\n");
26
27 }
28
29 /*打印b*/
30 void printb(struct node **b)
31 {
32 int i;
33 struct node *p=NULL;
34
35 for(i=0;i<N;i++)
36 {
37 p=b[i]->next;
38 while(p)
39 {
40 printf("%lf\t",p->data);
41 p=p->next;
42 }
43 }
44 }
45 /*初始化b*/
46 struct node **init_b(struct node **b)
47 {
48 int i;
49 b=(struct node**)malloc(sizeof(struct node*));
50 for(i=0;i<N;i++)
51 b[i]=(struct node*)malloc(sizeof(struct node*));
52
53 for(i=0;i<N;i++)
54 {
55 b[i]->next=NULL;
56 }
57
58 return b;
59 }
60
61 /*插入从a中得到元素,插入b,插入时排序*/
62 struct node** insert_b(struct node **b,struct node *p,int index)
63 {
64 struct node *r=NULL;
65 struct node *q=b[index]->next;
66 if(!q)
67 {
68 r=b[index];
69 }
70 else{
71 r=b[index];;
72 while(q)
73 {
74 if(q->data<p->data)
75 {
76 r=q;
77 q=q->next;
78 }
79 else break;
80 }
81 }
82 p->next=r->next;
83 r->next=p;
84
85 return b;
86 }
87
88 /*桶排序*/
89 struct node **bucket_sort(double *a)
90 {
91 int i,index;
92 struct node *p;
93
94 for(i=0;i<N;i++)
95 {
96 index=a[i]*10;
97 p=(struct node*)malloc(sizeof(struct node));
98 p->data=a[i];
99 p->next =NULL;
100
101 insert_b(b,p,index);
102 }
103 printb(b);
104 return b;
105 }
106
107 int main(void)
108 {
109 double a[]={0.78,0.17,0.39,0.26,0.72,0.94,0.21,0.12,0.23,0.68};
110 struct node **p;
111
112 printf("%s\n","排序前:");
113 print(a);
114 b=init_b(b);
115 printf("%s\n","排序后:");
116 p=bucket_sort(a);
117
118
119 return 0;
120 }

posted @ 2012-03-23 20:08  GOD!  阅读(272)  评论(0编辑  收藏  举报