排序函数模板 冒泡法

来源:互联网 发布:质量软件 编辑:程序博客网 时间:2024/05/22 18:55

  1. /* 
  2. *Copyright(c) 2016.烟台大学计算机与控制工程学院 
  3. *ALL rights  reserved. 
  4. *文件名称:test.cpp 
  5. *作者:隋宗涛
  6. *完成日期:2016年5月31 
  7. *问题描述:将数组a中的前size个元素按从小到大顺序排列 
  8. */  
  9. #include <iostream>  
  10. using namespace std;  
  11. template<class T>  
  12. void Sort(T *p,int n)  
  13. {  
  14.     int i,j;  
  15.     T t;  
  16.     for(i=1;i<n;i++)  
  17.         for(j=0;j<n-1-i;j++)  
  18.           if(*(p+j)>*(p+j+1))  
  19.          {  
  20.             t=*(p+j);  
  21.             *(p+j)=*(p+j+1);  
  22.             *(p+j+1)=t;  
  23.          }  
  24. }  
  25. int main()  
  26. {  
  27.     int i;  
  28.     int a[]={1,3,2,5,4,7};  
  29.     double b[]={3.1,2.1,4.2,2.4,8.2,4.2};  
  30.     Sort(a,6);  
  31.     Sort(b,6);  
  32.     for(i=0;i<6;i++)  
  33.         cout<<a[i]<<" ";  
  34.     cout<<endl;  
  35.     for(i=0;i<6;i++)  
  36.         cout<<b[i]<<" ";  
  37.     cout<<endl;  
  38.     return 0;  
  39. }  

运行结果:

0 0
原创粉丝点击