Skip to content

Instantly share code, notes, and snippets.

@wkschwartz
Last active December 16, 2015 09:08
Show Gist options
  • Save wkschwartz/5410476 to your computer and use it in GitHub Desktop.
Save wkschwartz/5410476 to your computer and use it in GitHub Desktop.
Experiments with an LSD Radix sort
#include <stdlib.h> /* malloc, free */
#include <stdio.h> /* NULL */
/**
* Stably sort and array of unsigned integers in place in linear time. Uses
* linear extra space. Return 0 on failure to allocate memory and 1 on success.
*
* Author: William Schwartz
*/
int sort(unsigned int a[], size_t len) {
if (len < 2)
return 1;
size_t zero = 0, one = 0, i;
unsigned int ai, d;
unsigned int *aux = (unsigned int *) malloc(len * sizeof(unsigned int));
if (aux == NULL)
return 0;
for (d = 1; d; d <<= 1) {
for (i = 0; i < len; one += a[i++] & d)
for (i = 0; i < len; i++) {
ai = a[i];
if (ai & d) aux[one++ ] = ai;
else aux[zero++] = ai;
}
for (i = 0; i < len; a[i] = aux[i++])
}
free(aux);
return 1;
}
@wkschwartz
Copy link
Author

Something is quite wrong with one += a[i++] & d.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment