Tuesday, 29 September 2015

Write a C rogram To Perform Radix Sort in Data Structure

1:  #include<stdio.h>  
2:  #include<conio.h>  
3:  void radix_sort(int arr[], int n);  
4:  void main()  
5:  {  
6:   int a[20],n,i;  
7:   clrscr();  
8:   printf("Enter the number of elements to be sorted:\n");  
9:   scanf("%d",&n);  
10:   printf("Enter the elements:\n");  
11:   for(i=0;i<n;i++)  
12:   {  
13:   scanf("%d",&a[i]);  
14:   }  
15:   printf("\nArray elements before Radix Sort:\n");  
16:   for(i=0;i<n;i++)  
17:   {  
18:   printf("%d\t",a[i]);  
19:   }  
20:   radix_sort(a,n);  
21:   printf("\nArray elemants after Radix Sort:\n");  
22:   for(i=0;i<n;i++)  
23:   {  
24:   printf("%d\t",a[i]);  
25:   }  
26:   getch();  
27:  }  
28:  void radix_sort(int arr[],int n)  
29:  {  
30:   int bucket[10][5],buck[10],b[10];  
31:   int i,j,k,l,num,div,large,passes;  
32:   div=1;  
33:   num=0;  
34:   large=arr[0];  
35:   for(i=0;i<n;i++)  
36:   {  
37:   if(arr[i]>large)  
38:   {  
39:    large=arr[i];  
40:   }  
41:   while(large>0)  
42:   {  
43:    num++;  
44:    large=large/10;  
45:   }  
46:   for(passes=0;passes<num;passes++)  
47:   {  
48:    for(k=0;k<10;k++)  
49:    {  
50:    buck[k]=0;  
51:    }  
52:    for(i=0;i<n;i++)  
53:    {  
54:    l=((arr[i]/div)%10);  
55:    bucket[l][buck[l]++]=arr[i];  
56:    }  
57:    i=0;  
58:    for(k=0;k<10;k++)  
59:    {  
60:    for(j=0;j<buck[k];j++)  
61:    {  
62:     arr[i++]=bucket[k][j];  
63:    }  
64:    }  
65:    div*=10;  
66:   }  
67:   }  
68:  }  

No comments:

Post a Comment