1
Bubble Sort
Algorithm › Sort
Repeatedly swap adjacent elements that are in the wrong order; after each pass the largest element "bubbles" to the end. Stop early if a pass makes no swap.
void bubbleSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
bool swapped = false;
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
swapped = true;
}
}
if (!swapped) break; // already sorted → O(n) best case
}
}