开发者

Swapping blocks of elements in an array

I am working on C++.. am in a need to swap two blocks of elements in an array..

Say, {1,2,3,4,5,6} is my input array.. block {4,5} should be moved to beginning and the output array should be like {4,5,1,2,3开发者_运维知识库,6}.. all i have is the start index and end index of the block {4,5}.. for doing this i am using a temp array, copying the blocks individually to temp array and moving it back to the original array, which is tedious

but i am sure there will be better methods to do this using memcpy or memmove.. any ideas?


There is a standard algorithm designed specifically for this task called std::rotate():

#include <algorithm>
#include <cstdio>

int main()
{
    int inputArray[] = {1, 2, 3, 4, 5, 6};
    ::printf("Before: ");
    for(int i = 0; i < 6; ++i)
    {
        ::printf("%d ", inputArray[i]);
    }
    ::printf("\n");

    int startIndex = 3; // refers to the number 4 in inputArray
    int endIndex = 5;   // refers one-past the number 5 in inputArray
    std::rotate(inputArray, inputArray+startIndex, inputArray+endIndex);

    ::printf("After: ");
    for(int i = 0; i < 6; ++i)
    {
        ::printf("%d ", inputArray[i]);
    }
    ::printf("\n");
}

Expected output:

Before: 1 2 3 4 5 6

After: 4 5 1 2 3 6

std::rotate() performs the rotation in-place via std::swap(), so there's no temporary array involved.


Bentley's "Programming Pearls" describes three algorithms for solving this problem. You can find slides for this specific problem here

http://www.cs.bell-labs.com/cm/cs/pearls/s02b.pdf

For example, the simplest algorithms would be the Reversal one. Just reverse the blocks that you need to swap, and then reverse the entire array. Done.

P.S. In your example "the entire array" would stand for the 1,2,3,4,5 subsequence (6 is not included), since these are the blocks that you need to swap.

Reverse the blocks:

3, 2, 1, 5, 4

Reverse the whole thing

4, 5, 1, 2, 3
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜