September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -1,23 +1,31 @@
|
|||
#include <stdio.h>
|
||||
#include <limits.h>
|
||||
#include <stdlib.h>
|
||||
#include <time.h>
|
||||
|
||||
typedef unsigned uint;
|
||||
#define swap(a, b) { tmp = a; a = b; b = tmp; }
|
||||
#define each(i, x) for (i = 0; i < x; i++)
|
||||
// Get size of statically allocated array
|
||||
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
|
||||
// Generate random number in the interval [M,N]
|
||||
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
|
||||
|
||||
static void swap(unsigned *a, unsigned *b) {
|
||||
unsigned tmp = *a;
|
||||
*a = *b;
|
||||
*b = tmp;
|
||||
}
|
||||
|
||||
/* sort unsigned ints */
|
||||
static void rad_sort_u(uint *from, uint *to, uint bit)
|
||||
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
|
||||
{
|
||||
if (!bit || to < from + 1) return;
|
||||
|
||||
uint *ll = from, *rr = to - 1, tmp;
|
||||
while (1) {
|
||||
unsigned *ll = from, *rr = to - 1;
|
||||
for (;;) {
|
||||
/* find left most with bit, and right most without bit, swap */
|
||||
while (ll < rr && !(*ll & bit)) ll++;
|
||||
while (ll < rr && (*rr & bit)) rr--;
|
||||
if (ll >= rr) break;
|
||||
swap(*ll, *rr);
|
||||
swap(ll, rr);
|
||||
}
|
||||
|
||||
if (!(bit & *ll) && ll < to) ll++;
|
||||
|
|
@ -31,27 +39,28 @@ static void rad_sort_u(uint *from, uint *to, uint bit)
|
|||
static void radix_sort(int *a, const size_t len)
|
||||
{
|
||||
size_t i;
|
||||
uint *x = (uint*) a;
|
||||
unsigned *x = (unsigned*) a;
|
||||
|
||||
each(i, len) x[i] ^= INT_MIN;
|
||||
rad_sort_u(x, x + len, INT_MIN);
|
||||
each(i, len) x[i] ^= INT_MIN;
|
||||
}
|
||||
for (i = 0; i < len; i++)
|
||||
x[i] ^= INT_MIN;
|
||||
|
||||
static inline void radix_sort_unsigned(uint *a, const size_t len)
|
||||
{
|
||||
rad_sort_u(a, a + len, (uint)INT_MIN);
|
||||
rad_sort_u(x, x + len, INT_MIN);
|
||||
|
||||
for (i = 0; i < len; i++)
|
||||
x[i] ^= INT_MIN;
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int len = 16, x[16], i;
|
||||
size_t len = 16, i;
|
||||
each(i, len) x[i] = rand() % 512 - 256;
|
||||
|
||||
radix_sort(x, len);
|
||||
srand(time(NULL));
|
||||
int x[16];
|
||||
|
||||
each(i, len) printf("%d%c", x[i], i + 1 < len ? ' ' : '\n');
|
||||
for (size_t i = 0; i < ARR_LEN(x); i++)
|
||||
x[i] = RAND_RNG(-128,127)
|
||||
|
||||
return 0;
|
||||
radix_sort(x, ARR_LEN(x));
|
||||
|
||||
for (size_t i = 0; i < ARR_LEN(x); i++)
|
||||
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue