|
| 1 | +#include "sort.h" |
| 2 | + |
| 3 | +int get_max(int *array, int size); |
| 4 | +void radix_counting_sort(int *array, size_t size, int sig, int *buff); |
| 5 | +void radix_sort(int *array, size_t size); |
| 6 | + |
| 7 | +/** |
| 8 | + * get_max - Get the maximum value in an array of integers. |
| 9 | + * @array: An array of integers. |
| 10 | + * @size: The size of the array. |
| 11 | + * |
| 12 | + * Return: The maximum integer in the array. |
| 13 | + */ |
| 14 | +int get_max(int *array, int size) |
| 15 | +{ |
| 16 | + int max, i; |
| 17 | + |
| 18 | + for (max = array[0], i = 1; i < size; i++) |
| 19 | + { |
| 20 | + if (array[i] > max) |
| 21 | + max = array[i]; |
| 22 | + } |
| 23 | + |
| 24 | + return (max); |
| 25 | +} |
| 26 | + |
| 27 | +/** |
| 28 | + * radix_counting_sort - Sort the significant digits of an array of integers |
| 29 | + * in ascending order using the counting sort algorithm. |
| 30 | + * @array: An array of integers. |
| 31 | + * @size: The size of the array. |
| 32 | + * @sig: The significant digit to sort on. |
| 33 | + * @buff: A buffer to store the sorted array. |
| 34 | + */ |
| 35 | +void radix_counting_sort(int *array, size_t size, int sig, int *buff) |
| 36 | +{ |
| 37 | + int count[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; |
| 38 | + size_t i; |
| 39 | + |
| 40 | + for (i = 0; i < size; i++) |
| 41 | + count[(array[i] / sig) % 10] += 1; |
| 42 | + |
| 43 | + for (i = 0; i < 10; i++) |
| 44 | + count[i] += count[i - 1]; |
| 45 | + |
| 46 | + for (i = size - 1; (int)i >= 0; i--) |
| 47 | + { |
| 48 | + buff[count[(array[i] / sig) % 10] - 1] = array[i]; |
| 49 | + count[(array[i] / sig) % 10] -= 1; |
| 50 | + } |
| 51 | + |
| 52 | + for (i = 0; i < size; i++) |
| 53 | + array[i] = buff[i]; |
| 54 | +} |
| 55 | + |
| 56 | +/** |
| 57 | + * radix_sort - Sort an array of integers in ascending |
| 58 | + * order using the radix sort algorithm. |
| 59 | + * @array: An array of integers. |
| 60 | + * @size: The size of the array. |
| 61 | + * |
| 62 | + * Description: Implements the LSD radix sort algorithm. Prints |
| 63 | + * the array after each significant digit increase. |
| 64 | + */ |
| 65 | +void radix_sort(int *array, size_t size) |
| 66 | +{ |
| 67 | + int max, sig, *buff; |
| 68 | + |
| 69 | + if (array == NULL || size < 2) |
| 70 | + return; |
| 71 | + |
| 72 | + buff = malloc(sizeof(int) * size); |
| 73 | + if (buff == NULL) |
| 74 | + return; |
| 75 | + |
| 76 | + max = get_max(array, size); |
| 77 | + for (sig = 1; max / sig > 0; sig *= 10) |
| 78 | + { |
| 79 | + radix_counting_sort(array, size, sig, buff); |
| 80 | + print_array(array, size); |
| 81 | + } |
| 82 | + |
| 83 | + free(buff); |
0 commit comments