In-place interleaving of the two halves of a string

后端 未结 6 1426
长发绾君心
长发绾君心 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:48

    Generically that problem is quite hard -- and it reduces to finding permutation cycles. The number and length of those varies quite a lot depending on the length.

    Cycles for in-place interleaving for 10 and 12 entry arrays

    The first and last cycles are always degenerate; the 10 entry array has 2 cycles of lengths 6 and 2 and the 12 entry array has a single cycle of length 10.

    Withing a cycle one does:

     for (i=j; next=get_next(i) != j; i=next) swap(i,next);
    

    Even though the function next can be implemented as some relatively easy formula of N, the problem is postponed to do book accounting of what indices have been swapped. In the left case of 10 entries, one should [quickly] find the starting positions of the cycles (they are e.g. 1 and 3).

提交回复
热议问题