ZetCode

C# Bubble Sort

last modified November 6, 2026

In this article we implement the bubble sort algorithm in C#. We sort numbers and strings in ascending and descending order, write a generic version, and compare its speed with the built-in Array.Sort method.

Sorting is arranging the elements of a collection in a specific order, for instance from the smallest to the largest. A sorting algorithm is the sequence of steps that produces this order.

Bubble sort algorithm

Bubble sort repeatedly walks through the array, compares each pair of adjacent elements, and swaps them if they are in the wrong order. After the first pass, the largest element is at the end of the array; it has bubbled up to its final position. Each next pass can therefore stop one element earlier.

PropertyValue
Best caseO(n), with the early exit optimization
Average and worst caseO(n²)
Extra memoryO(1), sorts in place
Stableyes

Bubble sort is simple to understand but slow. It is used for teaching and for very small or almost sorted inputs. Real programs use Array.Sort, List<T>.Sort, or LINQ OrderBy.

C# bubble sort example

The first example sorts an array of integers in ascending order.

Program.cs
int[] nums = [64, 34, 25, 12, 22, 11, 90, 5];

BubbleSort(nums);
Console.WriteLine(string.Join(" ", nums));

static void BubbleSort(int[] arr)
{
    int n = arr.Length;

    for (int i = 0; i < n - 1; i++)
    {
        for (int j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
            }
        }
    }
}

The method sorts the array in place; it does not return a new array.

for (int i = 0; i < n - 1; i++)
{
    for (int j = 0; j < n - i - 1; j++)

The outer loop counts the passes. An array of n elements needs at most n - 1 passes. The inner loop stops i elements before the end, because the last i elements are already in their final positions.

if (arr[j] > arr[j + 1])
{
    (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
}

When the left element is greater than its right neighbour, the two are swapped. The swap uses tuple deconstruction, so we do not need a temporary variable.

$ dotnet run
5 11 12 22 25 34 64 90

Early exit

If a pass completes without a single swap, the array is sorted and the remaining passes can be skipped. The following example adds this check and prints the array after each pass.

Program.cs
int[] nums = [5, 1, 4, 2, 8, 9, 10];

BubbleSort(nums);

static void BubbleSort(int[] arr)
{
    int n = arr.Length;
    int comparisons = 0;

    for (int i = 0; i < n - 1; i++)
    {
        bool swapped = false;

        for (int j = 0; j < n - i - 1; j++)
        {
            comparisons++;

            if (arr[j] > arr[j + 1])
            {
                (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
                swapped = true;
            }
        }

        Console.WriteLine($"pass {i + 1}: {string.Join(" ", arr)}");

        if (!swapped)
        {
            break;
        }
    }

    Console.WriteLine($"comparisons: {comparisons}");
}

The swapped flag is reset at the start of each pass and set when two elements are exchanged.

if (!swapped)
{
    break;
}

A pass without swaps ends the sorting. For an already sorted array, the algorithm makes just one pass of n - 1 comparisons, which gives the O(n) best case.

The input array is sorted after the second pass. The third pass makes no swaps and stops the algorithm. Without the check, the method would perform 6 passes and 21 comparisons.

$ dotnet run
pass 1: 1 4 2 5 8 9 10
pass 2: 1 2 4 5 8 9 10
pass 3: 1 2 4 5 8 9 10
comparisons: 15

Generic bubble sort

A generic method with a Comparison<T> delegate sorts elements of any type in any order.

Program.cs
string[] words = ["banana", "apple", "cherry", "date", "fig"];

BubbleSort(words, string.CompareOrdinal);
Console.WriteLine(string.Join(" ", words));

BubbleSort(words, (a, b) => string.CompareOrdinal(b, a));
Console.WriteLine(string.Join(" ", words));

double[] vals = [3.5, -1.2, 0.0, 7.25, 2.1];

BubbleSort(vals, (a, b) => b.CompareTo(a));
Console.WriteLine(string.Join(" ", vals));

static void BubbleSort<T>(T[] arr, Comparison<T> compare)
{
    int n = arr.Length;

    for (int i = 0; i < n - 1; i++)
    {
        bool swapped = false;

        for (int j = 0; j < n - i - 1; j++)
        {
            if (compare(arr[j], arr[j + 1]) > 0)
            {
                (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
                swapped = true;
            }
        }

        if (!swapped) break;
    }
}

The delegate returns a negative number, zero, or a positive number, like the CompareTo method. Elements are swapped when the result is positive.

BubbleSort(words, string.CompareOrdinal);

The string.CompareOrdinal method matches the delegate signature, so we pass it as a method group. It compares strings by their character codes.

BubbleSort(words, (a, b) => string.CompareOrdinal(b, a));

Swapping the arguments reverses the order; the words are sorted in descending order.

BubbleSort(vals, (a, b) => b.CompareTo(a));

The same method sorts doubles in descending order.

$ dotnet run
apple banana cherry date fig
fig date cherry banana apple
7.25 3.5 2.1 0 -1.2

Bubble sort is stable

A sorting algorithm is stable if elements with equal keys keep their original relative order. Bubble sort is stable because it swaps only elements that are strictly out of order.

Program.cs
List<Employee> staff =
[
    new("Paul", "IT"),
    new("Lucy", "Sales"),
    new("Robert", "IT"),
    new("Anna", "HR"),
    new("Peter", "Sales"),
    new("Jane", "HR"),
];

BubbleSort(staff, (a, b) => string.CompareOrdinal(a.Dept, b.Dept));

foreach (var e in staff)
{
    Console.WriteLine($"{e.Dept,-6} {e.Name}");
}

static void BubbleSort<T>(IList<T> items, Comparison<T> compare)
{
    for (int i = 0; i < items.Count - 1; i++)
    {
        bool swapped = false;

        for (int j = 0; j < items.Count - i - 1; j++)
        {
            if (compare(items[j], items[j + 1]) > 0)
            {
                (items[j], items[j + 1]) = (items[j + 1], items[j]);
                swapped = true;
            }
        }

        if (!swapped) break;
    }
}

record Employee(string Name, string Dept);

We sort employees by their department. The method works on any IList<T>, so it accepts a List<Employee> as well as an array.

if (compare(items[j], items[j + 1]) > 0)

Employees of the same department compare as equal and are never swapped. Paul stays before Robert, Lucy before Peter, and Anna before Jane, as in the input list. If we used >= 0 in the condition, the sort would lose its stability.

$ dotnet run
HR     Anna
HR     Jane
IT     Paul
IT     Robert
Sales  Lucy
Sales  Peter

Bubble sort vs Array.Sort

In the last example, we measure the time needed to sort 20,000 random integers.

Program.cs
#:property PublishAot=false

using System.Diagnostics;

var rnd = new Random(17);
int[] data = [.. Enumerable.Range(0, 20_000).Select(_ => rnd.Next(1_000_000))];

int[] a = [.. data];
var sw = Stopwatch.StartNew();
BubbleSort(a);
Console.WriteLine($"Bubble sort, random data: {sw.ElapsedMilliseconds} ms");

sw.Restart();
BubbleSort(a);
Console.WriteLine($"Bubble sort, sorted data: {sw.Elapsed.TotalMilliseconds:F3} ms");

int[] b = [.. data];
sw.Restart();
Array.Sort(b);
Console.WriteLine($"Array.Sort, random data:  {sw.Elapsed.TotalMilliseconds:F3} ms");

Console.WriteLine($"Same result: {a.SequenceEqual(b)}");

static void BubbleSort(int[] arr)
{
    int n = arr.Length;

    for (int i = 0; i < n - 1; i++)
    {
        bool swapped = false;

        for (int j = 0; j < n - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]);
                swapped = true;
            }
        }

        if (!swapped) break;
    }
}

We sort copies of the same random data with bubble sort and with Array.Sort. The second bubble sort call runs on data that is already sorted.

#:property PublishAot=false

File-based apps are published with Native AOT by default. The directive turns this off, so the release build does not pull in the AOT compiler package.

var rnd = new Random(17);

A fixed seed generates the same data on every run.

We run the program in the Release configuration, because debug builds are not optimized. The exact times depend on the machine, but the difference is clear. Bubble sort needs hundreds of milliseconds for random data. On sorted data, it finishes after a single pass. Array.Sort uses the introsort algorithm, which runs in O(n log n) time, and sorts the random data in about a millisecond.

$ dotnet run -c Release benchmark.cs
Bubble sort, random data: 378 ms
Bubble sort, sorted data: 0.042 ms
Array.Sort, random data:  0.982 ms
Same result: True

Source

Array.Sort method

In this article we have implemented the bubble sort algorithm in C#.

Other sorting algorithms in C#:

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.