-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathradix.c
94 lines (67 loc) · 2.06 KB
/
radix.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
/**
* Redix Sort written in C by Austin G Walters for austingwalters.com
*/
#include <stdio.h>
void printArray(int * array, int size){
int i;
printf("[ ");
for (i = 0; i < size; i++)
printf("%d ", array[i]);
printf("]\n");
}
int findLargestNum(int * array, int size){
int i;
int largestNum = -1;
for(i = 0; i < size; i++){
if(array[i] > largestNum)
largestNum = array[i];
}
return largestNum;
}
// Radix Sort
void radixSort(int * array, int size){
printf("\n\nRunning Radix Sort on Unsorted List!\n\n");
// Base 10 is used
int i;
int semiSorted[size];
int significantDigit = 1;
int largestNum = findLargestNum(array, size);
// Loop until we reach the largest significant digit
while (largestNum / significantDigit > 0){
printf("\tSorting: %d's place ", significantDigit);
printArray(array, size);
int bucket[10] = { 0 };
// Counts the number of "keys" or digits that will go into each bucket
for (i = 0; i < size; i++)
bucket[(array[i] / significantDigit) % 10]++;
/**
* Add the count of the previous buckets,
* Acquires the indexes after the end of each bucket location in the array
* Works similar to the count sort algorithm
**/
for (i = 1; i < 10; i++)
bucket[i] += bucket[i - 1];
// Use the bucket to fill a "semiSorted" array
for (i = size - 1; i >= 0; i--)
semiSorted[--bucket[(array[i] / significantDigit) % 10]] = array[i];
for (i = 0; i < size; i++)
array[i] = semiSorted[i];
// Move to next significant digit
significantDigit *= 10;
printf("\n\tBucket: ");
printArray(bucket, 10);
}
}
int main(){
printf("\n\nRunning Radix Sort Example in C!\n");
printf("----------------------------------\n");
int size = 12;
int list[] = {10, 2, 303, 4021, 293, 1, 0, 429, 480, 92, 2999, 14};
printf("\nUnsorted List: ");
printArray(&list[0], size);
radixSort(&list[0], size);
printf("\nSorted List:");
printArray(&list[0], size);
printf("\n");
return 0;
}