Files
homework/260202/冒泡排序优化版.cpp
newde 192c0f56aa 上傳檔案到「260202」
在冒泡排序的基础上加入一个判断 ,如何已经排好序的数组,可以直接break,增加效率。
2026-02-02 19:57:06 -05:00

36 lines
949 B
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <iostream>
using namespace std;
int main() {
int a[5] = {1, 2, 5, 4, 3}; // 举个例子
int n = 5;
for (int i = 0; i < n - 1; i++) {
// 1. 每一轮开始前,先设定一个标志位,假设它是“已经排好序”的
bool swapped = false;
for (int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
// 发生交换了
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
// 2. 只要有交换,就说明还没排好,标记为 true
swapped = true;
}
}
// 3. 关键判断如果这一轮走完swapped 还是 false说明没有发生任何交换
// 这意味着剩下的数字已经全都有序了,直接跳出循环
if (swapped == false) {
break;
}
}
cout << "优化后的排序结果: ";
for (int i = 0; i < n; i++) cout << a[i] << " ";
return 0;
}