用函数模板实现对n个数进行由小到大排序

#include<iostream>
using namespace std;

//用模板实现两个数值交换
template<class T>
void tswap( T *x, T *y)
{
int temp = *x;
*x = *y;
*y = temp;
}

//排序模板
template<class T>
void tsort(T arr)
{
int i,j;
T num1 = arr;
for (i=0;i<9;i++)
{
for (j=0;j<9;j++)
if (num1[j] > num1[j+1])
tswap(&num1[j], &num1[j+1]);
}
}

void main()
{

//调用测试
int i;
int num1[10] = {10,2,8,4,6,1,3,5,9,7}; // 整形数组
tsort(num1);
for (i=0;i<10;i++)
cout << num1[i] ;
cout << endl;

char arr[10] = "lang uage"; // 字符串数组
tsort(arr);
for (i=0;i<10;i++)
cout << arr[i] ;
cout << endl;

}

 

posted on 2022-10-26 20:25  进取  阅读(41)  评论(0编辑  收藏  举报