Karim O. Karim O. - 2 months ago 21
C# Question

Simple bubble sort c#

int[] arr = {800,11,50,771,649,770,240, 9};

int temp = 0;

for (int write = 0; write < arr.Length; write++)
{
for (int sort = 0; sort < arr.Length - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
Console.Write("{0} ", arr[write]);
}


All I am attempting to do is a simple bubble sort with this array. I would like to figure out why the sorting is screwed up.
In example, here is when the array is
{800,11,50,771,649,770,240, 9}
:

Here is what gets displayed:
11, 50, 649, 9, 649, 770, 771, 800


I am thinking that I might be missing something in the comparison.

Answer

No, your algorithm works but your Write operation is misplaced within the outer loop.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();
Comments