Bubble sort
Sort an integer array in ascending order using bubble sort.
Course progress
Problem 10 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [5, 1, 4, 2, 8]
Expected output
1 2 4 5 8
What is happening?
Adjacent out-of-order values are swapped on each pass. Larger values bubble right until the whole array is ordered.
Solution strategy
Build the right mental model
Repeatedly swap adjacent out-of-order values. After each pass, the largest unsorted value has moved to its final position.
Core concepts
sorting · nested loops
Complexity
Time O(n²), space O(1). The early-exit flag makes already sorted input O(n).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for bubble-sort
using System;
class Program
{
static void BubbleSort(int[] numbers)
{
for (int end = numbers.Length - 1; end > 0; end--)
{
bool swapped = false;
for (int i = 0; i < end; i++)
{
if (numbers[i] <= numbers[i + 1]) continue;
int temporary = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i + 1] = temporary;
swapped = true;
}
if (!swapped) return;
}
}
static void Main()
{
int[] values = { 5, 1, 4, 2, 8 };
BubbleSort(values);
Console.WriteLine(string.Join(" ", values));
}
}Knowledge check
Questions students often ask
What is the main idea behind bubble sort?
Repeatedly swap adjacent out-of-order values. After each pass, the largest unsorted value has moved to its final position.
What is the time and space complexity of this solution?
Time O(n²), space O(1). The early-exit flag makes already sorted input O(n).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.