Skip to content

Instantly share code, notes, and snippets.

@RMGiroux
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RMGiroux/89dfd9eb3582627b293e to your computer and use it in GitHub Desktop.
Save RMGiroux/89dfd9eb3582627b293e to your computer and use it in GitHub Desktop.
// Copyright 2015, Mike Giroux
// Licensed under Apache License 2.0 : http://www.apache.org/licenses/LICENSE-2.0
// Permission is explicitly granted to aggregate this solution with any other
// solutions to the Regehr Nibble-sort Challenge (http://blog.regehr.org/archives/1213)
// for benchmarking or pedagogical purposes, or any other purposes allowed by AL2.0.
unsigned long nibble_sort_word(unsigned long word) {
char nibble_counts[16] = {0};
unsigned long result = 0;
unsigned char nibble_index = 15;
for(int i = 0; i < sizeof(word)*2; ++i) {
nibble_counts[word&0x0F]++;
word>>=4;
}
for(unsigned long int i = 15; i > 0; --i) {
while (nibble_counts[i]--) {
result|=(i << nibble_index*4);
nibble_index--;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment