C# Program for Bubble Sort with Example and Explanation
for loops to repeatedly swap adjacent elements if they are in the wrong order, like if (arr[j] > arr[j + 1]) { swap } until the array is sorted.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int[] arr = {5, 3, 8, 4, 2}; for (int i = 0; i < arr.Length - 1; i++) { for (int j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } foreach (int num in arr) { Console.Write(num + " "); } } }
Dry Run
Let's trace the array [5, 3, 8, 4, 2] through the bubble sort code.
First pass comparisons and swaps
Compare 5 and 3, swap to get [3, 5, 8, 4, 2]; compare 5 and 8, no swap; compare 8 and 4, swap to get [3, 5, 4, 8, 2]; compare 8 and 2, swap to get [3, 5, 4, 2, 8]
Second pass comparisons and swaps
Compare 3 and 5, no swap; compare 5 and 4, swap to get [3, 4, 5, 2, 8]; compare 5 and 2, swap to get [3, 4, 2, 5, 8]
Third pass comparisons and swaps
Compare 3 and 4, no swap; compare 4 and 2, swap to get [3, 2, 4, 5, 8]
Fourth pass comparisons and swaps
Compare 3 and 2, swap to get [2, 3, 4, 5, 8]
| Pass | Array State |
|---|---|
| 1 | [3, 5, 4, 2, 8] |
| 2 | [3, 4, 2, 5, 8] |
| 3 | [3, 2, 4, 5, 8] |
| 4 | [2, 3, 4, 5, 8] |
Why This Works
Step 1: Compare adjacent elements
The code uses if (arr[j] > arr[j + 1]) to check if two neighbors are out of order.
Step 2: Swap if needed
If the left element is bigger, it swaps with the right one to move larger values toward the end.
Step 3: Repeat passes
Multiple passes ensure all elements bubble up to their correct position, sorting the entire array.
Alternative Approaches
using System; class Program { static void Main() { int[] arr = {5, 3, 8, 4, 2}; bool swapped; for (int i = 0; i < arr.Length - 1; i++) { swapped = false; for (int j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } if (!swapped) break; } foreach (int num in arr) Console.Write(num + " "); } }
using System; class Program { static void Main() { int[] arr = {5, 3, 8, 4, 2}; Array.Sort(arr); foreach (int num in arr) Console.Write(num + " "); } }
Complexity: O(n^2) time, O(1) space
Time Complexity
Bubble sort uses nested loops, each running up to n times, resulting in O(n^2) time in the worst and average cases.
Space Complexity
It sorts the array in place, so it uses only a constant amount of extra space, O(1).
Which Approach is Fastest?
Built-in Array.Sort() is fastest for practical use; optimized bubble sort can be faster than basic bubble sort on nearly sorted data.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic Bubble Sort | O(n^2) | O(1) | Learning sorting basics |
| Optimized Bubble Sort | O(n) best, O(n^2) worst | O(1) | Nearly sorted arrays |
| Array.Sort() | O(n log n) | O(n) or O(1) depending on implementation | Real-world sorting |