while it returns the correct result, it is not correct. there is no need to process the last element as the exchange has already happened and you are reprocessing swapped items:
int[] array = { 108, 23, 69, 420, 9 };
for (int j = 0; j < array.Length - 1; j++)
{
for (int i = 0; i < array.Length - j - 1; i++)
{
if (array[i] > array[i + 1])
{
int temporary = array[i + 1];
array[i + 1] = array[i];
array[i] = temporary;
}
}
}
Console.WriteLine("Sorted:");
foreach (int p in array)
{
Console.WriteLine(p);
}
and with early exit optimization:
int[] array = { 108, 23, 69, 420, 9};
for (int j = 0; j < array.Length - 1; j++)
{
bool swapped = false;
for (int i = 0; i < array.Length - j - 1; i++)
{
if (array[i] > array[i + 1])
{
int temporary = array[i + 1];
array[i + 1] = array[i];
array[i] = temporary;
swapped = true;
}
}
if (swapped == false)
break;
}