只有使用模板函数;如下是插入排序的模板函数
#include
using namespace std;
template
void Insert(T a[],int n){//直接插入排序
int i,j;
T temp;
for(i=1;i
if(a[i]
temp=a[i];
for(j=i-1;j>=0&&temp
a[j+1]=a[j];
a[j+1]=temp;
}
}
template
void show(T a[],int n){
cout<<"排序后序列:\n";
for(int i=0;i
cout<
cout<
}
int main()
{
int a[10]={3,5,66,12,5,9,32,15,8,4};
double b[10]={1.4,5.6,3,7,2.5,54,1.1,3.5,8,5.9};
Insert(a,10);
Insert(b,10);
show(a,10);
show(b,10);
return 0;
}
用模板
#include
using namespace std;
template < typename T>
void sort(T a[ ], int n)
{
T temp;
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - 1 - i; j++)
{
if (a[j] >a[j +1])
{
temp = a[j ];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int b = 0; b < n; b++)
{
cout << a[b] << " ";
}
cout<}
int main()
{
int num[5]= { 5, 6, 8, 2, 1 };
char c[6]={'a','f','d','z','r','e'};
double d[5]={10.2,6.8,1.5,102.5,34.1};
sort(num,5);
sort(c,6);
sort(d,5);
return 0;
}