-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.c
130 lines (122 loc) · 2.81 KB
/
radix_sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/*
* C program to Implement Radix Sort
*/
#include<stdio.h>
#include<stdlib.h>
int *Radix_sort(int *arr, int size);
int *Count_sort(int *arr, int size, int Exponent);
int maximum(int *arr,int length);
int minimum(int *arr,int length);
int main()
{
int i, size;
int *arr;
printf("Enter the array size: ");
scanf("%d",&size);
arr = (int *) malloc( sizeof( int ) * size );
if(arr==NULL)
{
exit(-1);//abnormal termination.
}
else
{
// Entering the array values
printf("Enter the array\n");
for(i = 0; i < size; i++)
{
printf("arr[ %d ] = ",i);
scanf("%d",&arr[i]);
}
printf("Array before sorting:\n");
for(i = 0; i < size; i++)
{
printf("arr[%d] = %d\n",i,arr[i]);
}
arr = Radix_sort(arr,size);
}
printf("ARRAY AFTER SORTING: \n");
for(int i=0;i<size;i++)
{
printf("arr[ %d ] = %d \n",i ,arr[i]);
}
}
int *Radix_sort(long int **data, int size)
{
int Max_of_key = maximum(data, size);
int Exponent = 1;
int count = 0;
while(Exponent <= Max_of_arr)
{
arr = Count_sort(arr, size, Exponent);
Exponent= Exponent* 10;
//uncomment the loop to see how sorting happens digit after moving from LSB to MSB.
/*
printf("ARRAY AFTER SORTING: %d digits from rightmost element\n",count);
for(int i=0;i<size;i++)
printf("arr[ %d ] = %d \n",i ,arr[i]);
count++;
*/
}
return arr;
}
int *Count_sort(int *arr, int size, int Exponent)
{
int range = 10;
int *frequency_array ;
frequency_array = (int*)malloc(sizeof(int)* range);
if(frequency_array == NULL)
{
exit(-1);
}
int sum=0;
for(int i=0; i<range; i++)
{
frequency_array[ i ]=0;
}
for(int i=0;i<size;i++)
{
frequency_array[ (arr[i]/Exponent)%10 ]++;
}
for(int i =0; i<range;i++)
{
sum = sum + frequency_array[i];
frequency_array[i] = sum;
}
int *new_arr;//new array to store the result.
new_arr = (int *)malloc(sizeof(int) *size);
if(new_arr == NULL)
{
exit(-1);
}
else
{
int pos;
for(int i=size-1; i>=0 ;i-- )
{
pos = frequency_array[(arr[i]/Exponent)%10]-1;
new_arr[ pos ] = arr[ i ];
frequency_array [(arr[i]/Exponent)%10]--;
}
}
return new_arr;
}
int maximum(int *arr, int length)
{
int max=INT_MIN;
for( int i=0 ; i<length ; i++ )
{
if(arr[i]>max)
max=arr[i];
}
return max;
}
int minimum(int *arr, int length)
{
int min=INT_MAX;
for( int i=0 ; i<length ; i++ )
{
if(arr[i]<min)
min=arr[i];
}
return min;
}