I have an array of containing a mixture of 0
s and 1
s. I want to rearrange the contents of the array so that as many even positions in the array contain 0
and odd positions contain 1
as possible, subject to the constraint that the number of 0
s and 1
s are unchanged. This means that if the number of 0
s exceeds the number of 1
s or vice versa then there will a block at the end of the rearranged array consisting of all-0
s or all-1
s. How can I do this in one pass, modifying the array in place?
For example:
Input: {0,1,1,0,1,0,1,0,1,1,1,0,0,1,0,1,1}
Output: {0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1}
You can just use the standard two-color sort algorithm for this; just edit the array references to map accesses to the first half of the array to even elements in your actual array, and accesses to the second half of the array to odd elements in your actual array (backwards). Basically, a[i]
becomes (assuming size
is even):
a[i < size/2 ? i * 2 : (size - i) * 2 - 1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With