Skip to content

Instantly share code, notes, and snippets.

@kbendick
Last active September 8, 2021 05:46
Show Gist options
  • Save kbendick/223ac295f6a4a9691579 to your computer and use it in GitHub Desktop.
Save kbendick/223ac295f6a4a9691579 to your computer and use it in GitHub Desktop.
Implementation of radix sort in c++
#include <queue>
int select_digit (int number, int place)
{ return number/place % 10; }
/*
Create an array of 10 buckets, each storing an empty queue (use ArrayQueue)
for every place (6 digit numbers: 1s, 10s, 100s, 1,000s, 10,000s, and 100,000s)
for every value in array a
put it in the correct bucket using select_digit (for the current place)
for every bucket (in the order 0 to 9)
move each of the values, from its queue, back into the array a (leaving all the queues empty)
*/
void radix_sort(int a[], int length) {
const int MAX_DIGIT = 6;
const int NUM_BINS = 10;
const int RADIX = 10;
std::queue<int> bins[NUM_BINS];
for (int d = 1, place = 1; d <= MAX_DIGIT; place *= RADIX, ++d) {
for (int i = 0; i < length; ++i) {
bins[select_digit(a[i], place)].push(a[i]);
}
int a_pos = 0;
for (int i = 0; i < NUM_BINS; ++i) {
while (!bins[i].empty()) {
a[a_pos++] = bins[i].front();
bins[i].pop();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment