How do the bit manipulations in this bit-sorting code work?

前端 未结 6 1477
时光取名叫无心
时光取名叫无心 2021-01-31 22:20

Jon Bentley in Column 1 of his book programming pearls introduces a technique for sorting a sequence of non-zero positive integers using bit vectors.

I have taken the p

6条回答
  •  盖世英雄少女心
    2021-01-31 23:13

    Starting with set():
    A right shift of 5 is the same as dividing by 32. It does that to find which int the bit is in.
    MASK is 0x1f or 31. ANDing with the address gives the bit index within the int. It's the same as the remainder of dividing the address by 32.
    Shifting 1 left by the bit index ("1<<(i & MASK)") results in an integer which has just 1 bit in the given position set.
    ORing sets the bit.
    The line "int sh = i>>SHIFT;" is a wasted line, because they didn't use sh again beneath it, and instead just repeated "i>>SHIFT"

    clr() is basically the same as set, except instead of ORing with 1<<(i & MASK) to set the bit, it ANDs with the inverse to clear the bit. test() ANDs with 1<<(i & MASK) to test the bit.

    The bitsort will also remove duplicates from the list, because it will only count up to 1 per integer. A sort that uses integers instead of bits to count more than 1 of each is called a radix sort.

提交回复
热议问题