Search code examples
arraysalgorithmshuffle

How to shuffle the array in-place


There is an array with equal number of odd and even numbers. The numbers are stored in no particular order. Is it possible to shuffle the array in-place (O(1) additional space) so that even numbers are directed to even indexes and odd numbers to odd indexes?

It is of course, trivial to implement using auxiliary storage, the constraint of not using one makes it tough. Plus there is no pattern, in problems like shuffling an array [a1,a2,a3..an,b1,b2...bn...n1,n2,n3...nn] to [a1,b1,c1..n1,a2,b2,c2...n2,...an,bn...nn], there is a fixed mapping, which enables one to do it. But there being no such pattern here, is it do-able at all?


Solution

  • Write two iterators. One iterates all array indices of odd numbers at even positions. The other iterates all even numbers at odd positions.

    Iterate over both simultaneously, and swap the items pointed to by the iterators until the end of the array. Should have O(n) performance.