Last active
May 17, 2019 19:07
-
-
Save boki1/df3fa168ea37b76150d824f5e69cbbbf to your computer and use it in GitHub Desktop.
Radix sort -> sort by bit mask
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 <stdio.h> | |
#include <stdlib.h> | |
#include <algorithm> | |
#define mask_default 1 << 3 | |
#define len(arr) sizeof(arr) / sizeof(*arr) | |
void r_sort(unsigned *start, unsigned *end, unsigned mask) { | |
if (start == end || !mask) | |
return; | |
unsigned *i = start, *j = end; | |
do { | |
while (i < j && ~*i & mask) ++i; | |
while (i < j && *j & mask) --j; | |
if (i < j) | |
std::swap(*i, *j); | |
} while (i < j); | |
if (*i & mask) --i; | |
if (~*j & mask) ++j; | |
unsigned n_mask = mask >> 1; | |
r_sort(start, i, n_mask); | |
r_sort(j, end, n_mask); | |
} | |
int main() { | |
unsigned nums[] = {6, 7, 1, 8, 3, 4, 9, 2, 5, 0}; | |
r_sort(nums, nums + len(nums) - 1, mask_default); | |
for (int i = 0; i < len(nums); ++i) | |
printf("%d ", *(nums + i)); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment