C#C
C#4y ago
surwren

Bubble Sort

I have two implementations of bubble sort here; one is the model answer and one is mine.

I am just wondering if my implementation would cover every possibility and sort correctly, or if I had somehow misapplied.

void BubbleSortModel(int[] arr)
{
    for (int i = 0; i < arr.Length - 1; i++)
    {
        for (int j = 0; j < arr.Length - 1; j++)
        {
            if (arr[j+1] < arr[j])
            {
                Swap(ref arr[j+1],ref arr[j]);
            }
        }
    }
}

void BubbleSortMine (int[] arr)
{
    for(int i = 0; i < arr.Length-1; i++)
    {
        for (int j = i + 1; j < arr.Length; j++)
        {
            if (arr[j] < arr[i])
            {
                Swap(ref arr[i], ref arr[j]);
            }

        }
    }
}

void Swap(ref int x, ref int y)
{
    int temp = x;
    x = y;
    y = temp;
}
Was this page helpful?