用函数模板实现对n个数从小到大排序

6271阅读 0评论2011-02-16 dongfs_love
分类:C/C++

  1. /**************************************************
  2. *filename:sort.cpp *
  3. *author:dongmeiZhao *
  4. *date:2011-02-16 *
  5. *description: this is a example about template *
  6. **************************************************/
  7. #include <iostream>

  8. using namespace std;

  9. template <class T>
  10. void smallToBig(T a[], T n)
  11. {
  12.     T temp;

  13.     //采用冒泡法进行排序

  14.     for (int i=0; i<n-1; i++)
  15.     {
  16.         for (int j=0; j<n-i-1; j++)
  17.         {        
  18.             if (a[j]>a[j+1])
  19.             {
  20.                 temp = a[j];
  21.                 a[j] = a[j+1];
  22.                 a[j+1] = temp;
  23.             }
  24.         }
  25.     }

  26. }

  27. int main()
  28. {
  29.     int n;//n个数据

  30.     cout<<"please input the number of data:1--10"<<endl;
  31.     cin>>n;

  32.     //输入n个数据

  33.     int dataBuf[10];
  34.     int dataTemp;
  35.     for (int num=0; num<n; num++)
  36.     {
  37.         cout<<"please input the"<<num<<"data"<<endl;
  38.         cin>>dataTemp;

  39.         dataBuf[num] = dataTemp;
  40.     }

  41.     smallToBig(dataBuf,n);//排序


  42.     //从小到大输出数据

  43.     for (int k=0; k<n; k++)
  44.     {
  45.         cout<<dataBuf[k]<<'\t';
  46.     }

  47.     return 0;
  48. }
上一篇:类的构造函数、析构函数与赋值函数
下一篇:计算机核心期刊排名及投稿信息