In-place interleaving of the two halves of a string

后端 未结 6 1353
长发绾君心
长发绾君心 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 08:06

    Ok lets start over. Here is what we are going to do:

    def interleave(string):
        i = (len(string)/2) - 1
        j = i+1
    
        while(i > 0):
            k = i
            while(k < j):
                tmp = string[k]
                string[k] = string[k+1]
                string[k+1] = tmp
                k+=2 #increment by 2 since were swapping every OTHER character
            i-=1 #move lower bound by one
            j+=1 #move upper bound by one
    

    Here is an example of what the program is going to do. We are going to use variables i,j,k. i and j will be the lower and upper bounds respectively, where k is going to be the index at which we swap.

    Example

    `abcd1234`
    
    i = 3 //got this from (length(string)/2) -1
    
    j = 4 //this is really i+1 to begin with
    
    k = 3 //k always starts off reset to whatever i is 
    
    swap d and 1
    increment k by 2 (k = 3 + 2 = 5), since k > j we stop swapping
    
    result `abc1d234` after the first swap
    
    i = 3 - 1 //decrement i
    j = 4 + 1 //increment j
    k= 2 //reset k to i
    
    swap c and 1, increment k (k = 2 + 2 = 4), we can swap again since k < j
    swap d and 2, increment k (k = 4 + 2 = 6), k > j so we stop
    //notice at EACH SWAP, the swap is occurring at index `k` and `k+1`
    
    result `ab1c2d34`
    
    i = 2 - 1
    j = 5 + 1
    k = 1
    
    swap b and 1, increment k (k = 1 + 2 = 3), k < j so continue
    swap c and 2, increment k (k = 3 + 2 = 5), k < j so continue
    swap d and 3, increment k (k = 5 + 2 = 7), k > j so were done
    
    result `a1b2c3d4`
    

    As for proving program correctness, see this link. It explains how to prove this is correct by means of a loop invariant.

    A rough proof would be the following:

    1. Initialization: Prior to the first iteration of the loop we can see that i is set to (length(string)/2) - 1. We can see that i <= length(string) before we enter the loop.
    2. Maintenance. After each iteration, i is decremented (i = i-1, i=i-2,...) and there must be a point at which i.
    3. Termination: Since i is a decreasing sequence of positive integers, the loop invariant i > 0 will eventually equate to false and the loop will exit.

提交回复
热议问题