三数排序两种方法编写程序,实现对三个整数由小到大排序,并输出。考虑整型、小数、字符等不同类型数的排序。
时间: 2023-12-28 19:04:18 浏览: 82
方法一:
```
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a, b, c;
cout << "请输入三个整数:";
cin >> a >> b >> c;
int arr[] = {a, b, c};
sort(arr, arr + 3);
cout << "排序后的结果为:" << arr[0] << " " << arr[1] << " " << arr[2] << endl;
return 0;
}
```
方法二:
```
#include <iostream>
using namespace std;
template <typename T>
void swap(T& a, T& b) {
T temp = a;
a = b;
b = temp;
}
template <typename T>
void sort(T arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
swap(arr[i], arr[j]);
}
}
}
}
int main() {
int a, b, c;
cout << "请输入三个数:";
cin >> a >> b >> c;
int arr1[] = {a, b, c};
sort(arr1, 3);
cout << "排序后的结果为:" << arr1[0] << " " << arr1[1] << " " << arr1[2] << endl;
double d1, d2, d3;
cout << "请输入三个小数:";
cin >> d1 >> d2 >> d3;
double arr2[] = {d1, d2, d3};
sort(arr2, 3);
cout << "排序后的结果为:" << arr2[0] << " " << arr2[1] << " " << arr2[2] << endl;
char c1, c2, c3;
cout << "请输入三个字符:";
cin >> c1 >> c2 >> c3;
char arr3[] = {c1, c2, c3};
sort(arr3, 3);
cout << "排序后的结果为:" << arr3[0] << " " << arr3[1] << " " << arr3[2] << endl;
return 0;
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![](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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)