-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.c
86 lines (75 loc) · 1.89 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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define INPUT_SIZE 1000000
#define BASE 10
int calc_max(int[], int);
void count_sort(int[], int, int);
void radix_sort(int[], int);
int main(){
int arr[INPUT_SIZE];
int i;
for(i = 0; i < INPUT_SIZE; i++){
arr[i] = random();
}
clock_t start_time = clock();
radix_sort(arr, INPUT_SIZE);
clock_t end_time = clock();
double execution_time = (double)(end_time - start_time) / CLOCKS_PER_SEC;
/*for(i = 0; i < INPUT_SIZE; i++){
printf("%i\n", arr[i]);
}*/
printf("\nExecution Time = %f\n", execution_time);
return 0;
}
/*
** calculate the maximum element in the array
*/
int calc_max(int A[], int n){
int max = A[0];
int i;
for(i = 1; i < n; i++){
if(A[i] > max)
max = A[i];
}
return max;
}
/*
** use count sort to sort from rigtmost bit to leftmost bit
*/
void count_sort(int A[], int n, int exp){
int output[n], aux[BASE];
//Initialize auxiliary array
int i;
for(i = 0; i < BASE; i++){
aux[i] = 0;
}
//Fill auxiliary array with the number of repetitions for each element in A
for(i = 0; i < n; i++){
aux[(A[i] / exp) % BASE]++;
}
//Modify auxiliary to have the number of elements less than each element in A
for(i = 1; i < BASE; i++){
aux[i] = aux[i] + aux[i - 1];
}
//Put each element from A into its correct position in output
for(i = n - 1; i >= 0; i--){
output[aux[(A[i] / exp) % BASE] - 1] = A[i];
aux[(A[i] / exp) % BASE]--;
}
//Copy array output to array A
for(i = 0; i < n; i++){
A[i] = output[i];
}
}
/*
** radix sort with count sort as a subroutine as it is a stable algorithm
*/
void radix_sort(int A[], int n){
//Calcuate the maximum number in the array
int max = calc_max(A, n);
int i;
for(i = 1; max / i > 0; i *= BASE){
count_sort(A, n, i);
}
}