用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]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
int main() {
int arr[] = {5, 2, 9, 1, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
输出结果:
Sorted array: 1 2 5 5 6 9
在这个例子中,我们定义了一个名为“bubbleSort”的函数,该函数接受一个整数数组和数组大小作为参数。我们使用两个嵌套的循环来遍历数组并比较相邻的元素。如果它们的顺序不正确,我们就使用“swap”函数交换它们的位置。最后,我们在“main”函数中调用“bubbleSort”函数并输出排序后的数组
原文地址: https://www.cveoy.top/t/topic/cRRf 著作权归作者所有。请勿转载和采集!