用同一个函数名对n(n<=10)个数据进行从小到大排序,数据类型可以是整数、浮点数,用函数重载实现
时间: 2023-05-27 09:06:11 浏览: 58
C++代码如下:
```c++
#include <iostream>
using namespace std;
void sort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
void sort(double arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
double tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
int main() {
int arr1[] = {4, 2, 6, 1, 8};
double arr2[] = {3.5, 1.2, 6.7, 2.8, 5.6};
sort(arr1, 5);
sort(arr2, 5);
for (int i = 0; i < 5; i++) {
cout << arr1[i] << " ";
}
cout << endl;
for (int i = 0; i < 5; i++) {
cout << arr2[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:
```
1 2 4 6 8
1.2 2.8 3.5 5.6 6.7
```
其中,sort函数被重载了两次,分别用于整数数组和浮点数数组的排序。在主函数中,分别调用sort函数对整数数组和浮点数数组进行排序,并输出结果。
阅读全文