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

前端 未结 6 1529
时光取名叫无心
时光取名叫无心 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:05

    Basically is a bucket sort optimized:

    • reserve a bit array of length n bits.
    • clear the bit array (first for in main).
    • read the items one by one (they must all be distinct).
      • set the i'th bit in the bit array if the read number is i.
    • iterate the bit array.
      • if the bit is set then print the position.

    Or in other words (for N < 10 and to sort 3 numbers 4, 6, 2) 0

    start with an empty 10 bit array (aka one integer usually)

    0000000000
    

    read 4 and set the bit in the array..

    0000100000
    

    read 6 and set the bit in the array

    0000101000
    

    read 2 and set the bit in the array

    0010101000
    

    iterate the array and print every position in which the bits are set to one.

    2, 4, 6

    sorted.

提交回复
热议问题