It will do it. The result differs from the proposed output, but it is equal to the given rules (the text of the problem does not include the word "sort", only in the end you need to move all 0 , you can even positions and 1 you can in odd positions. You do not need to "compact" them). It's a little harder to do this "compaction".
static void Main(string[] args) { var input = new[] { 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1 }; var lastEvenToMove = -1; var lastOddToMove = -1; for (int i = 0; i < input.Length; i++) { bool needEven = i % 2 == 0; bool isEven = input[i] == 0; if (needEven == isEven) { continue; } if (needEven) { if (lastEvenToMove != -1) { var old = input[lastEvenToMove]; input[lastEvenToMove] = 1; input[i] = 0; lastEvenToMove = old; } else { input[i] = lastOddToMove; lastOddToMove = i; } } else { if (lastOddToMove != -1) { var old = input[lastOddToMove]; input[lastOddToMove] = 0; input[i] = 1; lastOddToMove = old; } else { input[i] = lastEvenToMove; lastEvenToMove = i; } } } while (lastEvenToMove != -1) { var old = input[lastEvenToMove]; input[lastEvenToMove] = 0; lastEvenToMove = old; } while (lastOddToMove != -1) { var old = input[lastOddToMove]; input[lastOddToMove] = 1; lastOddToMove = old; } Console.WriteLine(@"{{{0}}}", String.Join(", ", input.Select(p => p.ToString()))); }
I keep a stack of odds and a stack of even elements that need moving, and I use them when I need an even / even number. Two stacks are stored in the input array, so there is no additional space (except for two "heads" of two stacks, which are two additional integers). I think the worst case is O(1.5n) for time (for example, all elements are 1 , half of the elements are βpushedβ on the stack, and then it needs to be discarded because there was no empty space) and O(1) for space.
Output:
{0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1}