#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
// 外层循环控制遍历的轮数
for (int i = 0; i < n - 1; i++) {
// 内层循环进行相邻元素的比较和交换
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 如果前一个元素大于后一个元素,则交换它们
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "排序前:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
bubbleSort(arr, n);
cout << "排序后:" << endl;
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
bubbleSort
函数:该函数实现了冒泡排序算法。它通过多次遍历数组,每次将最大的元素“冒泡”到数组的末尾。
main
函数:这是程序的入口,定义了一个数组并调用 bubbleSort
函数对其进行排序。排序前后分别输出数组的内容以便对比。
交换逻辑:在内层循环中,使用了临时变量 temp
来交换两个元素的位置。
上一篇:opencv c++
下一篇:c++ 协程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站