写一个c++的冒泡排序
时间: 2023-11-02 20:18:46 浏览: 31
好的,以下是C++实现的冒泡排序:
```c++
#include <iostream>
using namespace std;
void bubble_sort(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[] = { 64, 25, 12, 22, 11 };
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n);
cout << "排序后的数组: \n";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
```
在以上代码中,`bubble_sort` 函数接受一个整数数组和其大小,使用嵌套的for循环来进行排序。在每个内部循环中,它比较相邻的元素并将它们交换(如果需要的话)以便按升序排序。最终,`main` 函数将数组传递给 `bubble_sort` 函数进行排序,然后输出排序后的结果。
相关问题
写一个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 << "排序后的数组:\n";
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
```
在此代码中,我们定义了一个名为`bubbleSort`的函数来对一个整数数组进行冒泡排序。该函数接受两个参数:一个整数数组和数组的长度。在`bubbleSort`函数中,我们使用了两个嵌套的循环来比较和交换相邻的元素,直到整个数组都被排序。最后,我们在`main`函数中定义了一个整数数组,然后调用`bubbleSort`函数对其进行排序,并输出排序后的结果。
希望这可以帮助您!
写一个c++ 冒泡排序
下面是 C++ 冒泡排序的代码:
```cpp
#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;
}
```
该程序使用了双重循环来实现冒泡排序。外层循环控制排序次数,内层循环控制每次排序的比较和交换。在每次内层循环中,如果前一个元素比后一个元素大,则交换它们的位置。经过多次排序后,数组中的元素将按升序排列。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)