I was trying a basic sorting exercise and I was hoping I could receive some help with what is probably a basic logic error.
int[] numbers = new int[] { 2, 5, 11, 38, 24, 6, 9, 0, 83, 7 };
for (int loop = 0; loop < numbers.Length; loop++)
{
Console.WriteLine(numbers[loop]);
}
Console.WriteLine("Performing a bubble sort");
bool flag = false;
do
{
for (int loop = 0; loop < numbers.Length - 1; loop++)
{
if (numbers[loop] > numbers[loop + 1])
{
int temporary = numbers[loop];
numbers[loop] = numbers[loop + 1];
numbers[loop + 1] = temporary;
flag = true;
}
}
} while (flag == false);
for (int loop = 0; loop < numbers.Length; loop++)
{
Console.WriteLine(numbers[loop]);
}
There are two issues with your code. The first, as has been pointed out, is that you need to loop as long as
flag == true. That would have been a lot more clear if you had given it a more expressive name.madeASwapor something like that makes it obvious:do while(madeASwap).The other issue is that you need to reset the flag before running the inner loop. Without that, just checking for
falseends after a single iteration, and checking fortrueresults in an infinite loop.In short: reset your flag, and loop while it’s true.