Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 基数排序。为什么是异或?_C_Radix Sort - Fatal编程技术网

C 基数排序。为什么是异或?

C 基数排序。为什么是异或?,c,radix-sort,C,Radix Sort,我正在研究基数排序算法,但我无法理解一些原始源代码 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 wi

我正在研究基数排序算法,但我无法理解一些原始源代码

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;
}
static void rad\u sort\u(无符号*from,无符号*to,无符号位)
{
如果(!bit | | to=rr)中断;
掉期(*ll,*rr);
}
如果(!(位&*ll)和&ll>=1;
rad_sort_(from、ll、bit);
rad_sort_(ll、to、bit);
}
/*对有符号整数排序:翻转最高位、按无符号排序、翻转回位*/
静态空基排序(int*a,常量大小)
{
尺寸i;
无符号*x=(无符号*)a;
对于(i=0;i
我不知道它为什么用这条线 (i=0;i x[i]^=INT_MIN

我知道它的xor,但我不理解这个操作符在这个上下文中的用法

它正在切换MSB(最高有效位)

根据我的理解,INT_MIN根据使用的编译器和系统的不同而不同,但它通常是十六进制的0x8000000,二进制的计算结果是10000…0

如果将任何位与1进行异或,则切换该位:

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
因此,当执行该行时,x[i]的最高位被切换。如果是零,现在是一。如果是一,现在是零

简而言之:XOR任意值,X,用
0
,得到原始值X。XOR任意值X,用1,得到X的补码!十,

 Y | X A
===+====
 X   X 0
!X   X 1

值得一提的是,这段代码在其递归中有一个糟糕的堆栈溢出。要正确实现此算法,必须先递归到较小的一半,然后再对较大的一半进行尾部递归(或直接
转到顶部;
)。