Last active
December 16, 2015 09:08
-
-
Save wkschwartz/5410476 to your computer and use it in GitHub Desktop.
Experiments with an LSD Radix sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Something is quite wrong with
one += a[i++] & d
.