2

I was studying the radix sort algorithm but I could not understand some of the original source code.

static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
    if (!bit || to < from + 1) return;

    unsigned *ll = from, *rr = to - 1,tmp;
    while (1) {
        /* 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);
    }

    if (!(bit & *ll) && ll < to) ll++;
    bit >>= 1;

    rad_sort_u(from, ll, bit);
    rad_sort_u(ll, to, bit);
}

/* sort signed ints: flip highest bit, sort as unsigned, flip back */
static void radix_sort(int *a, const size_t len)
{
    size_t i;
    unsigned *x = (unsigned*) a;

    for (i = 0; i < len; i++) 
            x[i] ^= INT_MIN;

    rad_sort_u(x, x + len, INT_MIN);

    for (i = 0; i < len; i++) 
            x[i] ^= INT_MIN;
}

I don't know why its using this line for (i = 0; i < len; i++) x[i] ^= INT_MIN;

I know its xor but I don't understand the use of this operator in this context.

4

1 回答 1

2

It is toggling the MSB (most significant bit).

INT_MIN is different depending on the compiler and system in use, to my understanding, but it will generally be something like 0x80000000 in hex, which would evaluate to something like 10000...0 in binary.

If you XOR any bit with one, you toggle it:

eg: if y = A xor B

y | A B
==+====
0   0 0
1   0 1
1   1 0
0   1 1

y | A 1
==+====
1   0 1
0   1 1

Therefore
A xor 1 = !A

So, when that line is executed, the highest bit of x[i] is being toggled. If it was zero, it is now one. If it was one, it is now zero.

In short: XOR any value, X, with 0, you get the original value, X. XOR any value X, with 1, you get the complement of X, !X.

 Y | X A
===+====
 X   X 0
!X   X 1
于 2012-05-08T16:47:56.307 回答