帮我写一个c++冒泡排序算法
以下是一个简单的C++冒泡排序算法实现:
#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[] = { 5, 1, 4, 2, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
在这个算法中,我们使用了两个嵌套循环来遍历数组中的每个元素。在内部循环中,我们比较相邻的两个元素,如果它们的顺序不正确,就交换它们的位置。在外部循环中,我们重复这个过程,直到所有元素都被排序为止
原文地址: https://www.cveoy.top/t/topic/gdky 著作权归作者所有。请勿转载和采集!