Bucket or radix sort in C.

 

01  #include <stdio.h> 
02 #define MAX 100
03 #define SHOWPASS
04
05 void print(int *a, int n)
06 {
07 int i;
08 for (i = 0; i < n; i++)
09 printf("%dt;", a[i]);
10 }
11 void radix_sort(int *a, int n)
12 {
13 int i, b[MAX], m = 0, exp = 1;
14 for (i = 0; i < n; i++)
15 {
16 if (a[i] > m)
17 m = a[i];
18 }
19 while (m / exp > 0)
20 {
21 int box[10] = { 0 };
22 for (i = 0; i < n; i++)
23 box[a[i] / exp % 10]++;
24 for (i = 1; i < 10; i++)
25 box[i] += box[i - 1];
26 for (i = n - 1; i >= 0; i--)
27 b[--box[a[i] / exp % 10]] = a[i];
28 for (i = 0; i < n; i++)
29 a[i] = b[i];
30 exp *= 10;
31 #ifdef SHOWPASS
32 printf("nnPASS : ");
33 print(a, n);
34 #endif
35 }
36 }
37 int main()
38 {
39 int arr[MAX];
40 int i, num;
41 printf("nEnter total elements (num < %d) : ", MAX);
42 scanf("%d", &num);
43 printf("n Enter %d Elements : ", num);
44
45 for (i = 0; i < num; i++)
46 scanf("%d", &arr[i]);
47 printf("n ARRAY : ");
48 print(&arr[0], num);
49 radix_sort(&arr[0], num);
50 printf("n nSORTED : ");
51 print(&arr[0], num);
52
53 return 0;
54 }
 
 OUTPUT :

Enter total elements (num < 100) : 5

Enter 5 Elements :
111
32
15463
2355
6

ARRAY : 111 ;32 ;15463 ;2355 ;6 ;

PASS : 111 ;32 ;15463 ;2355 ;6 ;

PASS : 6 ;111 ;32 ;2355 ;15463 ;

PASS : 6 ;32 ;111 ;2355 ;15463 ;

PASS : 6 ;32 ;111 ;2355 ;15463 ;

PASS : 6 ;32 ;111 ;2355 ;15463 ;

SORTED : 6 ;32 ;111 ;2355 ;15463 ;

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.