Search code examples
arrayssortingshufflein-place

zip an array without creating subarrays


Is it possible to "zip" an array without using 2 subarrays? Normally the result of zipping 2 arrays would look something like this

a1 = [1,2,3]
a2 = [4,5,6]
a3 = zip(a1, a2)
a3 == [1,4,2,5,3,6]

However, I don't have 2 subarrays and all I am given is an input (lets say creating arrays is not a capability at this moment), and I want to zip the array in place. e.g.

a1 = [1,2,3,4,5,6]
zip(a1)
a1 == [1,4,2,5,3,6]

My current algorithm doesn't do this properly (it results in a sequence where the first half is zipped properly, but the second half is zipped in reverse)

array = [1,2,3,4,5,6,7,8]
a = array[0]
b = array[1]
i = 0, j = array.length / 2
while (i + 2 < j)
    array[i] = a
    array[i + 1] = b
    swap(array, i + 1, i + 2)
    swap(array, i + 1, j)
    i += 2, j += 1
    a = b
    b = array[i + 1]

array == [1,5,2,6,4,8,3,7]

Complete answers aren't necessary - a guide into the general direction is preferred.


Solution

  • The straightforward way is by opening room for each element on swap, by shifting to the right:

    void swap(int *array, int left, int right) {
         int tmp = array[right];
         while (right > left)
              array[right] = array[--right];
         array[right] = tmp;
    }
    

    Now you just have to adjust your for loop indexes:

    void zip(int *array, int sz) {
         int i, j;
         for (i = 1, j = sz/2; j < sz; i += 2, ++j)
              swap(array, i, j);
    }