问题描述:
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