In-place interleaving of the two halves of a string

后端 未结 6 1463
长发绾君心
长发绾君心 2021-02-20 07:30

Given a string of even size, say:

abcdef123456

How would I interleave the two halves, such that the same string would become

6条回答
  •  感情败类
    2021-02-20 07:58

    Alright, here's a rough draft. You say you don't just want an algorithm, but you are taking hints, so consider this algorithm a hint:

    Length is N.

    k = N/2 - 1.

    1) Start in the middle, and shift (by successive swapping of neighboring pair elements) the element at position N/2 k places to the left (1st time: '1' goes to position 1).

    2) --k. Is k==0? Quit.

    3) Shift (by swapping) the element at N/2 (1st time:'f' goes to position N-1) k places to the right.

    4) --k.

    Edit: The above algorithm is correct, as the code below shows. Actually proving that it's correct is waaay beyond my capabilities, fun little question though.

    #include 
    #include 
    
    int main(void)
    {
        std::string s("abcdefghij1234567890");
        int N = s.size();
        int k = N/2 - 1;
        while (true)
        {
    
            for (int j=0; j

提交回复
热议问题