The first problem is that your algorithm isn't correct. If there are only 'w'
s or only 'r'
s in the array, you still write both, a 'w'
and an 'r'
to the array at the end of the outer loop.
And in that case, your code will actually take Θ(N²)
time. Let's say everything is 'r'
:
char[] A = new char[] { 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r' };
int lastRedPosition = A.Length - 1;
int firstWhitePosition = 0;
for (int i = firstWhitePosition ; i < A.Length; i++)
{
// determine the first red from the right e.g. the lastred, ending at the firstwhite position
for (int j = lastRedPosition; j > firstWhitePosition; j--)
{
if (A[j] == 'r')
{
lastRedPosition = j;
break;
}
}
j
is A.length - 1 - i
now. In the first iteration, it found an 'r'
immediately, later, there have been written i
'w'
s to the last entries of the array and lastRedPosition
was the index of the first of these, so except for the first iteration,
j` is decremented exactly once.
for (int k = firstWhitePosition; k < lastRedPosition; k++)
{
if (A[k] == 'w')
{
firstWhitePosition = k;
break;
}
}
firstWhitePosition
is always 0. k
is incremented until it becomes lastRedPosition
without finding a 'w'
, so firstWhitePosition
is not changed. Thus k
is incremented A.length - 1 - i
times.
Sum over i
for a total of ~N²/2
increments of k
.
A[firstWhitePosition] = 'r';
A[lastRedPosition] = 'w';
}
You must check whether A[firstWhitePosition]
actually is 'w'
and A[lastRedPosition]
actually 'r'
. If not, you're done. And your outer loop should check firstWhitePosition < lastRedPosition
.