Back to Learn

Bubble Sort

O(n2) average and worst case. O(1) space. Stable sort.

Unsorted
Comparing
Swapping
Sorted

Implementation

void BubbleSort(int[] arr)
{
    for (var i = arr.Length - 1; i > 0; i--)
    {
        var swapped = false;

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

        if (!swapped) break;
    }
}

How it works

Algorithm

Repeatedly walks through the array, compares adjacent elements, and swaps them if they are in the wrong order. Each pass bubbles the largest unsorted element to its final position.

When to use

Teaching tool. In practice, almost never. It is the simplest sorting algorithm to understand and implement, which makes it good for learning, but it is too slow for real workloads.

Share this site

QR Code for cardasac.com

cardasac.com

Scan with your phone camera