c++ 编写数组排序的函数
时间: 2024-05-10 16:18:13 浏览: 9
以下是使用 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++
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n);
int main() {
int arr[] = { 3, 1, 4, 2, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
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;
}
}
}
}
```
输出结果:
```
1 2 3 4 5
```