Bubble Sorter Algorithm

The Bubble Sort Algorithm is a simple and widely known sorting algorithm used to sort elements in an array, list, or any other data structure. The algorithm works by repeatedly iterating through the list and comparing each adjacent pair of elements. If the elements are out of order, they are swapped, and the process continues until the entire list is sorted. Bubble Sort gets its name from the way smaller elements "bubble" to the top of the list (i.e., the beginning of the array) as larger elements "sink" to the bottom (i.e., the end of the array) during the sorting process. This algorithm has a straightforward implementation and is easy to understand, making it an excellent choice for teaching sorting concepts to beginners. However, Bubble Sort Algorithm has its limitations, as it is not the most efficient sorting algorithm for large datasets. It has a worst-case and average-case time complexity of O(n^2), where n is the number of items being sorted. This means that the algorithm's performance degrades substantially as the size of the input increases. In practical applications, other sorting algorithms such as Quick Sort, Merge Sort, or Heap Sort are often preferred due to their better performance characteristics. Despite its limitations, Bubble Sort Algorithm remains a fundamental sorting technique and serves as a great introduction to the world of algorithms and computer science.
using System.Collections.Generic;

namespace Algorithms.Sorters.Comparison
{
    /// <summary>
    /// Class that implements bubble sort algorithm.
    /// </summary>
    /// <typeparam name="T">Type of array element.</typeparam>
    public class BubbleSorter<T> : IComparisonSorter<T>
    {
        /// <summary>
        /// Sorts array using specified comparer,
        /// internal, in-place, stable,
        /// time complexity: O(n^2),
        /// space complexity: O(1),
        /// where n - array length.
        /// </summary>
        /// <param name="array">Array to sort.</param>
        /// <param name="comparer">Compares elements.</param>
        public void Sort(T[] array, IComparer<T> comparer)
        {
            for (var i = 0; i < array.Length - 1; i++)
            {
                var wasChanged = false;
                for (var j = 0; j < array.Length - i - 1; j++)
                {
                    if (comparer.Compare(array[j], array[j + 1]) > 0)
                    {
                        var temp = array[j];
                        array[j] = array[j + 1];
                        array[j + 1] = temp;
                        wasChanged = true;
                    }
                }

                if (!wasChanged)
                {
                    break;
                }
            }
        }
    }
}

LANGUAGE:

DARK MODE: