C move memory parts inplace

前端 未结 6 826
轮回少年
轮回少年 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:13

    This solution is O(N) and uses already processed source locations as scratch space to use when ranges overlap. It will swap contents of source and destination up to the point when it reaches the start of destination, then it will proceed copying from the scratch space generated before. The second loop restores the clobbered region after each character of the scratch space is used.

    move(A,N, src_idx, dst_idx, len)
    {
      first_dst_idx=dst_idx;
      first_src_idx=src_idx;
      mlen=0;
      while(src_idx != first_dst_idx && len > 0)
      {
        temp = A[dst_idx];
        A[dst_idx] = A[src_idx];
        A[src_idx] = temp;
        src_idx=(src_idx+1) mod N;
        dst_idx=(dst_idx+1) mod N;
        len--; mlen++;
      }
      src_idx = first_src_idx;
      while(len > 0)
      {
        A[dst_idx] = A[src_idx];
        A[src_idx] = A[first_dst_idx];
        src_idx=(src_idx+1) mod N;
        dst_idx=(dst_idx+1) mod N; 
        first_dst_idx=(first_dst_idx+1) mod N;
        len--;
      }
      while(mlen > 0)
      { // restore reamining scratch space
        A[src_idx] = A[first_dst_idx];
        src_idx=(src_idx+1) mod N;
        first_dst_idx=(first_dst_idx+1) mod N;
        mlen--;
      }
    }
    

提交回复
热议问题