Reputation: 188
Whats the most efficient way of implementing a Radix-sorting algorithm in C, that sorts by the binary representation (on an array of integeres)?
I would like to be able to give a number n representing the number of elements to sort, and also a value b telling how many binary digits you want to be interpreted as one digit in the sorting algorithm, so that you can vary the n and b depending on how big your numbers are.
Any suggestions how to implement this?
Upvotes: 1
Views: 1667
Reputation: 19395
Any suggestions how to implement this?
#include <string.h>
#include <limits.h>
void radixsort(unsigned int array[], int n, int b)
{
unsigned int place[n], *a0 = array, *a1 = place, *a;
int values = 1<<b, start[values+1], bmask = values-1, shift;
for (shift = 0; shift < sizeof (int) * CHAR_BIT; shift += b)
{
int i;
memset(start, 0, sizeof start);
for (i = 0; i < n; ++i) ++start[(a0[i]>>shift&bmask)+1];
for (i = 2; i < values; ++i) start[i] += start[i-1];
for (i = 0; i < n; ++i) a1[start[a0[i]>>shift&bmask]++] = a0[i];
a = a0, a0 = a1, a1 = a;
}
if (a0 != array) memcpy(array, a0, sizeof place);
}
It turns out that rcgldr's description of the algorithm fits this implementation, except that the starting offsets are computed not until they're needed.
Upvotes: 1
Reputation: 28921
The approach I use is to make a single pass over the data to create a set (matrix) of histograms of the number of occurrences of a bit pattern in each of the bit fields used to sort by. This is the "counting" step of a radix sort. Then the histograms are converted into starting index offsets by starting with zero and accumulating a sum of the counts for each entry in a histogram set. Then the radix sort is performed for each bit field, lowest to highest order, using the starting indexes associated with that bit field and incrementing each index as it's used. Wiki article:
http://en.wikipedia.org/wiki/Counting_sort
Upvotes: 0