radix sort pog
This commit is contained in:
79
radix.c
Normal file
79
radix.c
Normal file
@@ -0,0 +1,79 @@
|
||||
#include "include/types.h"
|
||||
#include "include/radix.h"
|
||||
|
||||
int _seperate_pos_neg(lsort_array_i* array, lsort_array_i* pos_array, lsort_array_i* neg_array) {
|
||||
for (int i = 0; i < array->count; i++) {
|
||||
if ((0x80000000 & array->items[i]) == 0x80000000) {
|
||||
lsort_array_i_append(neg_array, array->items[i]);
|
||||
} else {
|
||||
lsort_array_i_append(pos_array, array->items[i]);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int _sort_items(lsort_array_i* numbers, lsort_array_i_array* buckets) {
|
||||
int byte_check = 0x0000000F;
|
||||
|
||||
for (int i = 0; i < 8; i++) {
|
||||
// Loop through the list of numbers and append them to their respective buckets for this 4-byte chunk
|
||||
for (int item_index = 0; item_index < numbers->count; item_index++) {
|
||||
int* current_number = &numbers->items[item_index];
|
||||
lsort_array_i* bucket = buckets->items[(*current_number >> (i * 4)) & byte_check];
|
||||
|
||||
lsort_array_i_append(bucket, *current_number);
|
||||
}
|
||||
|
||||
numbers->count = 0;
|
||||
|
||||
// Add the bucketed numbers back to the original array after emptying it
|
||||
for (int bucket_number = 0; bucket_number < buckets->count; bucket_number++) {
|
||||
lsort_array_i* bucket = buckets->items[bucket_number];
|
||||
|
||||
for (int bucket_item = 0; bucket_item < bucket->count; bucket_item++) {
|
||||
lsort_array_i_append(numbers, bucket->items[bucket_item]);
|
||||
}
|
||||
|
||||
bucket->count = 0;
|
||||
}
|
||||
|
||||
// Repeat for each 4-byte chunk...
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int lsort_radix(lsort_array_i* array, lsort_array_i* return_array) {
|
||||
if (array->count <= 0) return 1;
|
||||
|
||||
// Seperate positive and negative numbers
|
||||
lsort_array_i positive_numbers = {0};
|
||||
lsort_array_i negative_numbers = {0};
|
||||
|
||||
if (_seperate_pos_neg(array, &positive_numbers, &negative_numbers)) return 2;
|
||||
|
||||
// Create buckets
|
||||
lsort_array_i_array buckets = {0};
|
||||
for (int i = 0; i < 16; i++) {
|
||||
lsort_array_i* bucket = lsort_array_i_create();
|
||||
lsort_array_i_array_append(&buckets, bucket);
|
||||
}
|
||||
|
||||
// Sort each set of numbers using those buckets
|
||||
_sort_items(&negative_numbers, &buckets);
|
||||
_sort_items(&positive_numbers, &buckets);
|
||||
|
||||
// Add each array of numbers to the return array
|
||||
for (int i = 0; i < negative_numbers.count; i++) {
|
||||
lsort_array_i_append(return_array, negative_numbers.items[i]);
|
||||
}
|
||||
|
||||
for (int i = 0; i < positive_numbers.count; i++) {
|
||||
lsort_array_i_append(return_array, positive_numbers.items[i]);
|
||||
}
|
||||
|
||||
// Destroy the buckets
|
||||
lsort_array_i_array_destroy(&buckets);
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user