用 c++ 写一个冒泡排序
时间: 2024-05-03 19:20:02 浏览: 13
以下是用C语言编写的冒泡排序示例代码:
```
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = {5, 2, 8, 4, 7, 1, 3, 9, 6};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的数组:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果:
```
排序后的数组:
1 2 3 4 5 6 7 8 9
```
相关问题
用C++写一个冒泡排序
冒泡排序是一种简单的排序算法,其基本思想是通过相邻元素之间的比较和交换来把小的元素往前面移动,大的元素往后面移动,从而达到排序的目的。以下是用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, 8, 3, 9, 1};
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;
}
```
在上面的代码中,bubbleSort()函数用于实现冒泡排序的算法,它接收一个整数数组和数组长度作为参数。在函数中,通过两层循环来遍历整个数组,对相邻元素进行比较和交换。在主函数中,我们定义一个整数数组并初始化,通过调用bubbleSort()函数对数组进行排序,并输出排序后的结果。
用c++写一个冒泡排序
好的,以下是用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[] = {64, 34, 25, 12, 22, 11, 90};
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;
}
```
解释一下:
首先定义了一个 `bubbleSort` 函数,接收一个整型数组和数组的长度作为参数,函数内部实现了冒泡排序算法。
然后在 `main` 函数中定义了一个整型数组 `arr`,并计算了数组的长度 `n`,接着调用 `bubbleSort` 函数进行排序。
最后输出排序后的数组。
希望能够帮到你!
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)