C move memory parts inplace

前端 未结 6 824
轮回少年
轮回少年 2021-02-07 09:52

I am implementing several datastructures and one primitive I want to use is the following: I have a memory chunk A[N] (it has a variable length, but I take 100 for my examples)

6条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-07 10:07

    Here's an O(n2) algorithm is pretty straightforward - just rotate the entire buffer a single byte, and then repeat that as many times as steps you want to:

    void rotateBuffer(char *buffer, int size, int steps)
    {
        char tmp;
        int i;
    
        for (i = 0; i < steps; i++)
        {
            tmp = buffer[size - 1];
            memmove(buffer + 1, buffer, size - 1);
            buffer[0] = tmp;
        }
    }
    

    It won't be fast, but its get the job done, and with only constant temporary storage.

    Edit:

    If you need to rotate just a sub-part of the buffer relative to a static underlying 'background', as discussed below in the comments, you can do something like this:

    void rotateBuffer(int count, int start, int length)
    {
        int i;
        int j;
        int index;
    
        // rotate 'count' bytes
        for (i = 0; i < count; i++)
        {
            // rotate by a single byte
            for (j = length - 1; j >= 0; j--)
            {
                index = start + i + j;
                buf[(index + 1) % SIZE] = buf[index % SIZE];
            }
        }
    }
    

    I think it might have a problem if you need to rotate the entire buffer, but in that case you could just fall back to the code above.

提交回复
热议问题