1
0
forked from newde/homework
Files
homework/260202/冒泡排序优化版.cpp

36 lines
1.0 KiB
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 = a.length;
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 max = a[j];
a[j] = a[j + 1];
a[j + 1] = max;
// 2. 只要有交换,就说明还没排好,标记为 true
swapped = true;
}
}
// 3. 关键判断如果这一轮走完swapped 还是 false说明没有发生任何交换
// 这意味着剩下的数字已经全都有序了,直接跳出循环
if (swapped == false) {
break;
}
}
cout << "优化后的排序结果: ";
for (int i = 0; i < n; i++) cout << a[i] << " ";
return 0;
}