Bubble Sorting with C-Sharp Example

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, indicating that the list is sorted. Here’s an example implementation of bubble sort in C#:

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);
}

In this implementation, we start with the full array and repeatedly pass through it, comparing adjacent elements and swapping them if they are in the wrong order. We keep track of whether any swaps were made on each pass, and if no swaps were made, we know the array is sorted and we can stop. The time complexity of bubble sort is O(n^2) in the worst case, so it is not efficient for large arrays.