Bubble Sort Algorithm in C# with Generic Method Example

Introduction

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted.

Bubble Sortis the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.

How Bubble Sort Works?

  1. First Pass: Bubble Sort starts by comparing the first two elements of the list. If the first element is greater than the second one, they are swapped. Then it moves to compare the second and third elements, and so on, until the end of the list is reached. The largest element is placed in its correct position, i.e., the end of the array.
    First Pass
  2. Second Pass: After the first pass, the largest element will be at the end of the list (if sorted in ascending order), as it "bubbles up" to its correct position. now place the second largest element at the correctposition.
     Second Pass
  3. Repeat Until Sorted: The algorithm repeats this process for each element in the list, one pass at a time until no more swaps are needed. This indicates that the list is sorted.
    Repeat Until Sorted

Time Complexity

The time complexity of the Bubble Sort algorithm is O(n^2) in the worst-case scenario, where n is the number of elements in the list. This is because it involves nested loops, resulting in comparisons and swaps for each element in the list.

Let's see its code in C# with a generic method

using System;

public class Sorter<T> where T : IComparable<T>
{
    public static void BubbleSort(T[] array)
    {
        int n = array.Length;
        bool swapped;
        
        do
        {
            swapped = false;
            
            for (int i = 0; i < n - 1; i++)
            {
                if (array[i].CompareTo(array[i + 1]) > 0)
                {
                    Swap(ref array[i], ref array[i + 1]);
                    swapped = true;
                }
            }
            
            n--;
        } while (swapped);
    }

    private static void Swap(ref T first, ref T second)
    {
        T temp = first;
        first = second;
        second = temp;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int[] intArray = { 6, 0, 3, 5 };
        Sorter<int>.BubbleSort(intArray);
        Console.WriteLine("Sorted integer array:");
        PrintArray(intArray);

        string[] stringArray = { "banana", "apple", "orange", "grape", "kiwi" };
        Sorter<string>.BubbleSort(stringArray);
        Console.WriteLine("Sorted string array:");
        PrintArray(stringArray);
    }

    static void PrintArray<T>(T[] array)
    {
        foreach (var item in array)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine();
    }
}

Conclusion

Bubble Sort, although not the most efficient sorting algorithm, is easy to understand and implement. It's suitable for small datasets or as an educational tool to learn about sorting algorithms. However, for larger datasets, more efficient algorithms like Quick Sort or Merge Sort are preferred.


Similar Articles