就地交叉数组元素[a1a2b1b2]->[a1b1a2b2]

问题描述:

If [a1,a2,a3...,an,b1,b2...bn] is given input change this to [a1,b1,a2,b2.....an,bn] , solution should be in-place

解答:

第一步,交换中间一组元素.  再交换中间两组元素. 持续进行知道获得结果.

 

例子:

a1 a2 a3 a4 b1 b2 b3 b4
a1 a2 a3 b1 a4 b2 b3 b4
a1 a2 b1 a3 b2 a4 b3 b4
a1 b1 a2 b2 a3 b3 a4 b4

 

代码:

   1:  int interleave(int arr[], int len) {
   2:    int n = len/2;
   3:    for (int i = 1; i < n; i++) { // my step no.
   4:      for (int j = 0; j < i; j++) { // no. of swaps
   5:        swap(arr, n-i+2*j, n-i+2*j+1);
   6:      }
   7:    }
   8:  }

 

 

来自: carrercup

posted on 2013-10-23 10:24  苯苯吹雪  阅读(617)  评论(0编辑  收藏  举报

导航