6-2 数组排序输出(函数模板)
对于输入的每一批数,按从小到大排序后输出。
一行输入为一批数,第一个输入为数据类型(1表示整数,2表示字符型数,3表示有一位小数的浮点数,4表示字符串,0表示输入结束),第二个输入为该批数的数量size(0<size<=10),接下来为size个指定类型的数据。
输出将从小到大顺序输出数据。
函数接口定义:sort函数将接受size个数据,将它们从小到大排序后存在a指向的一段连续空间中。
template <class T>
void sort(T *a, int size);
裁判测试程序样例:
#include <iostream>
#include <string>
using namespace std;
/* 请在这里填写答案 */
template <class T>
void display(T* a, int size){
for(int i=0; i<size-1; i++) cout<<a[i]<<' ';
cout<<a[size-1]<<endl;
}
int main() {
const int SIZE=10;
int a[SIZE];
char b[SIZE];
double c[SIZE];
string d[SIZE];
int ty, size;
cin>>ty;
while(ty>0){
cin>>size;
switch(ty){
case 1:sort(a,size); display(a,size); break;
case 2:sort(b,size); display(b,size); break;
case 3:sort(c,size); display(c,size); break;
case 4:sort(d,size); display(d,size); break;
}
cin>>ty;
}
return 0;
}
输入样例:
1 3 3 2 1
2 2 a A
3 3 1.5 2.6 2.2
4 2 bca abc
0
输出样例:
1 2 3
A a
1.5 2.2 2.6
abc bca
1 template <class T> 2 void sort(T *a,int size) 3 { 4 5 for(int i=0;i<size;i++) 6 {cin>>a[i];} 7 for(int i=0;i<size;i++) 8 { 9 for(int j=i+1;j<size;j++) 10 { 11 if (a[i]>a[j]) 12 { 13 T temp; 14 temp=a[i]; 15 a[i]=a[j]; 16 a[j]=temp; 17 } 18 } 19 } 20 21 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结