← 返回题目页

A1107 冒泡排序plus

标程

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++) cin >> a[i];

    // 每一轮:未排序部分从左往右扫,左边比右边小就交换(把最小值往右推)
    for (int round = 0; round < n - 1; round++) {
        bool swapped = false;
        for (int i = 0; i < n - 1 - round; i++) {
            if (a[i] < a[i + 1]) {
                swap(a[i], a[i + 1]);
                swapped = true;
            }
        }

        // 输出这一轮冒泡之后的数组
        for (int i = 0; i < n; i++) cout << a[i] << ' ';
        cout << '\n';

        // 这一轮没有发生交换,说明已经有序,停止
        if (!swapped) break;
    }
    return 0;
}

动画演示