用c加加写一个冒泡序列
时间: 2024-05-03 07:21:46 浏览: 115
以下是用C++编写的冒泡排序代码:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 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, 25, 12, 22, 11};
int size = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, size);
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
输出结果:
Sorted array: 11 12 22 25 64
在这个示例中,我们定义了一个名为bubbleSort
的函数,该函数采用指向整数数组的指针arr
和数组的大小size
作为参数。在函数体内,我们使用两个嵌套的循环来实现冒泡排序。外部循环迭代数组中的每个元素,内部循环比较相邻的元素并交换它们,如果它们不按升序排列。每次迭代外部循环,我们可以将数组的最大元素移动到最后。最终,我们得到了一个按升序排列的数组。
相关推荐

















