C++数组排序冒泡写法
时间: 2023-11-14 10:07:51 浏览: 54
C++数组排序冒泡写法如下:
```c++
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;
}
}
}
}
```
相关问题
c++数组排序
可以使用C++ STL中的sort函数来排序数组。以下是一个示例代码:
```c++
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {5, 2, 1, 6, 3, 4};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr + n);
for (int i = 0; i < n; ++i) {
cout << arr[i] << " ";
}
return 0;
}
```
输出结果为:1 2 3 4 5 6。
在这个示例中,我们使用sort函数来对数组进行排序。sort函数接受两个参数:数组的起始地址和结束地址。在这个示例中,我们使用arr和arr+n作为这两个参数。因此,sort函数将按升序对数组进行排序。
c++ 二维数组的冒泡排序
好的,以下是 C++ 二维数组的冒泡排序示例代码:
```C++
#include <iostream>
using namespace std;
void bubbleSort(int arr[][3], int size)
{
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3 - j - 1; k++) {
if (arr[i][k] > arr[i][k + 1]) {
swap(arr[i][k], arr[i][k + 1]);
}
}
}
}
}
int main()
{
int arr[3][3] = { {3, 2, 1}, {6, 5, 4}, {9, 8, 7} };
int size = 3;
cout << "Before sorting:" << endl;
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
bubbleSort(arr, size);
cout << "After sorting:" << endl;
for (int i = 0; i < size; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
输出结果:
```
Before sorting:
3 2 1
6 5 4
9 8 7
After sorting:
1 2 3
4 5 6
7 8 9
```
这个示例代码中,我们定义了一个 3x3 的二维数组,然后使用 bubbleSort 函数对其进行冒泡排序。在 bubbleSort 函数中,我们使用了三重循环来遍历整个二维数组,并在内层循环中使用交换操作来实现冒泡排序。最后,我们在 main 函数中输出排序前后的数组。