Back to Writing
NOTESalgorithmsortingbubble-sortcsharpdata-structures
Algorithm - Bubble Sort
April 14, 2020•Updated Feb 17, 2026
Bubble Sort is a simple sorting algorithm.
How it works:
- Compare adjacent elements
- Swap if they're in the wrong order
- Repeat until no more swaps are needed
Time Complexity: O(n^2)
Space Complexity: O(1)
Implementation:
void BubbleSort(int[] arr) {
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]) {
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
Example:
Initial: [64, 34, 25, 12, 22]
Pass 1: [34, 25, 12, 22, 64]
Pass 2: [25, 12, 22, 34, 64]
Pass 3: [12, 22, 25, 34, 64]
Pass 4: [12, 22, 25, 34, 64]