bsort example from programming pearls

筅森魡賤 提交于 2019-12-11 05:19:45

问题


In Programming Pearls there is an algorithm that sorts varying length arrays but sorts in time proportional to the sum of their length. For example, if we have a record array x[0...n-1], and each record has an integer length and a pointer to array bit[0...length-1].

The code is implemented this way:

void bsort(l, u, depth){
    if (l >= u)
        return ;
    for (i = l; i <= u; i++){
        if (x[i].length < depth)
            swap(i, l++);
    }
    m = l;
    for (int i = l; i < u; i++){
        if (x[i].bit[depth] == 0)
            swap(i, m++);
    }
    bsort(l, m - 1, depth + 1);
    bsort(m, u, depth + 1);
}

My question is that, given the record:

x[6] = {"car", "bus", "snow", "earth", "dog", "mouse"}

I know how to get the string length, but what about with a bit array? How could I make a bit array suitable for this string array? And even x[i].bit[depth] how can I implement this?


回答1:


Arrays of chars (or any other type, for that matter) are also arrays of bits - chars are made of bits, after all. So you don't have to create a separate array, you just have to find a way to access a given bit in the array. For that, you'll have to use some bit manipulations. You can find a few examples of how this could be done here: Any smarter way to extract from array of bits?.

Basically, you first have to figure out the byte the required bit is at, and then get that specific bit's value. Something along:

char* array = "the array";
int required_bit = 13;
int bit = required_bit & 0x7;  // get the bit's offset in its byte
int byte = required_bit >> 3;  // get the bit's byte
int val = (array[byte] >> bit) & 0x1; // check if the bit is 1

Now wrap this in a function (possibly with additional bound checks, to make sure the given required_bit is not outside of the array), and use with x[i].



来源:https://stackoverflow.com/questions/7775963/bsort-example-from-programming-pearls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!