From 192c0f56aab7216508acbd629d226065f2e8ab66 Mon Sep 17 00:00:00 2001 From: newde Date: Mon, 2 Feb 2026 19:57:06 -0500 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E5=82=B3=E6=AA=94=E6=A1=88=E5=88=B0?= =?UTF-8?q?=E3=80=8C260202=E3=80=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 在冒泡排序的基础上加入一个判断 ,如何已经排好序的数组,可以直接break,增加效率。 --- 260202/冒泡排序优化版.cpp | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 260202/冒泡排序优化版.cpp diff --git a/260202/冒泡排序优化版.cpp b/260202/冒泡排序优化版.cpp new file mode 100644 index 0000000..e38ebc0 --- /dev/null +++ b/260202/冒泡排序优化版.cpp @@ -0,0 +1,35 @@ +#include +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; +}