免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 781 | 回复: 0
打印 上一主题 下一主题

c++ sorts template [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-03-05 15:21 |只看该作者 |倒序浏览

               
               
                冒泡排序
#include iostream.h>
template class T>
void bubblesort(T *p, int n)
{
for(int i=0;in;i++)
coutp" ";  //output the value before sort
coutendl;
int flag=1,count=0;
for(int i=0;(in-1)&&flag;i++)//attention the condition of loop
{
count++;//count the number of loop
flag=0;
for(int j=0;jn-1-i;j++)//attention the condition of loop
if(p[j]>p[j+1])
{
T temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
flag=1;
}
}
coutcountendl;
}
template class T>
void print(T *arr, int n)
{
for(int i=0;in;i++)
coutarr" ";
coutendl;
}
int main()
{
int arr[4]={42,52,55,68};
int iarr[5];
for(int i=0;i5;i++)
{
iarr=rand()%100;
}
bubblesort(iarr,5);
coutendl;
print(iarr,5);
}
插入排序
#include iostream.h>
template class T>
void insertsort(T *p, int n)
{
for(int i=0;in;i++)//output the values before sort
coutp" ";
coutendl;
int count=0;
for(int j=1;jn;j++)
{
T temp=p[j];
while(j>0&&(tempp[j-1]))
{p[j]=p[--j];
//count++;
}
p[j]=temp;
}
}
template class T>
void print(T *arr, int n)
{
for(int i=0;in;i++)
coutarr" ";
coutendl;
}
int main()
{
int arr[4]={42,52,55,68};
int iarr[5];
for(int i=0;i5;i++)
{
iarr=rand()%100;
}
insertsort(iarr,5);
coutendl;
print(iarr,5);
}
选择排序
#include iostream.h>
template class T>
void selectsort(T *p, int n)
{
for(int i=0;in;i++)//output the values before sort
coutp" ";
coutendl;
int count=0;
for(int j=0;jn-1;j++)
{
int h=j;
for(int k=j+1;kn;k++)
{if(p[h]>p[k])
h=k;
count++;
}
if(h!=j)
{
T temp=p[h];
p[h]=p[j];
p[j]=temp;
}
}
cout"the count= "countendl;
}
template class T>
void print(T *arr, int n)
{
for(int i=0;in;i++)
coutarr" ";
coutendl;
}
int main()
{
int arr[4]={42,52,55,68};
int iarr[5];
for(int i=0;i5;i++)
{
iarr=rand()%100;
}
selectsort(iarr,5);
coutendl;
print(iarr,5);
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/45689/showart_489885.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP