Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Bubble Sort

1 topic · 28 Nov 2026
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.

C++
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
    }
}