is my while condition bad?
No, your for
loop condition is incorrect. Look at the loop here and consider what that says about the value of i
within the body of the loop.
for (int i = 0; i < list.Length; i++)
That ensures that list[i]
is always valid. But you're using list[i + 1]
, so you need to make sure that i + 1
is a valid index into the array. The simplest way to do that is to just reduce the limit in the condition:
for (int i = 0; i < list.Length - 1; i++)
That will remove the exception, but you'll be left with this while
loop:
while (list[i] > list[i+1])
{
list[i] = list[i + 1];
}
You don't modify the value of i
within the loop, which means it's only ever going to execute once - as soon as you've executed the body of that loop, the condition will become false. So it would be clearer to write it as an if
statement:
if (list[i] > list[i+1])
{
list[i] = list[i + 1];
}
Now I suspect that's not really what you want - you probably want to swap values rather than just assigning, and you probably want a single loop, but that's rather beyond the scope of the immediate question.