Algorithms

Bubble Sort: An Introduction to the Simple Sorting Algorithm in C#

In this post, we will explore the Bubble Sort algorithm and its implementation in C#. Bubble Sort is a simple sorting algorithm that repeatedly swaps adjacent elements if they are in the wrong order.

Let’s start with a simple implementation of the bubble sort algorithm:

public static void BubbleSort(int[] arr)
{
    int n = arr.Length;
    bool swapped;
    do
    {
        swapped = false;
        for (int i = 1; i < n; i++)
        {
            if (arr[i - 1] > arr[i])
            {
                int temp = arr[i];
                arr[i] = arr[i - 1];
                arr[i - 1] = temp;
                swapped = true;
            }
        }
        n--;
    } while (swapped);
}

Bubble sort works by repeatedly swapping adjacent elements in the array if they are in the wrong order. The algorithm compares each pair of adjacent elements and swaps them if they are in the wrong order. This process is repeated until the array is sorted.

Overall, the bubble sort algorithm has a time complexity of O(n^2), where n is the number of elements in the array. This makes it inefficient for large arrays. However, it can be useful for small arrays or for teaching purposes due to its simplicity.

You should never have the need to implement any sorting algorithm since they are available in .NET out of the box. However, it’s good to understand them just in case somebody asks you how it works in an interview.