Python 与 C++ 冒泡排序代码对比
作者:野牛程序员:2025-12-08 15:53:21算法阅读 2200
Python 与 C++ 冒泡排序代码对比
Python 与 C++ 冒泡排序代码并列对比
Python 版本
# Python:冒泡排序(Bubble Sort)
# ----------------------------------------
# 原理:
# 通过相邻元素两两比较,将较大值逐步“冒”到右侧。
# 每一轮都会把当前未排序部分的最大值放到末尾。
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# 测试
data = [5, 1, 4, 2, 8]
bubble_sort(data)
print("排序结果:", data)C++ 版本
/*
C++:冒泡排序(Bubble Sort)
----------------------------------------
原理:
相邻元素进行比较,若次序错误则交换,
每一轮将当前未排序区域中的最大值推到右侧。
*/
#include <iostream>
#include <vector>
using namespace std;
void bubble_sort(vector<int>& arr) {
int n = arr.size();
for(int i = 0; i < n - 1; i++) {
for(int j = 0; j < n - 1 - i; j++) {
if(arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
vector<int> data = {5, 1, 4, 2, 8};
bubble_sort(data);
cout << "排序结果:";
for(int x : data) cout << x << " ";
cout << endl;
return 0;
}Python 与 C++ 代码差异要点
| 对比点 | Python | C++ |
|---|---|---|
| 交换方式 | a, b = b, a | swap(a, b) |
| 数据结构 | 动态列表(list) | vector 或数组 |
| 代码风格 | 通俗简洁 | 更接近底层逻辑 |
| 内存管理 | 自动 | 受类型与容器影响 |
| 静态类型 | 动态类型 | 强类型 |
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

