冒泡排序

   1:  /*
   2:  *Author:justinzhang
   3:  *Email:uestczhangchao@gmail.com
   4:  *Time:2011年5月11日16:17:52
   5:  *Discription:冒泡排序算法, change to cpp and add template @2012-9-4 22:08:26
   6:  */
   7:   
   8:   
   9:  #include <iostream>
  10:  using namespace std;
  11:   
  12:  template<typename T> void b_swap(T& x, T& y)
  13:  {
  14:      T tmp = x;
  15:      x = y;
  16:      y = tmp;
  17:  }
  18:   
  19:  template<typename T> void bubblesort(T A[],int len)
  20:  {
  21:      int i,j;
  22:      int flag = 0;
  23:      for(i=1; i<=len-1;i++)
  24:      {
  25:          flag = 0;
  26:          for(j=1;j<=len-i;j++)
  27:          {
  28:              if(A[j]>A[j+1])
  29:              {
  30:                  b_swap<T>(A[j],A[j+1]);
  31:                  flag = 1;
  32:              }
  33:          }
  34:   
  35:          if(flag==0)
  36:              break;
  37:      }
  38:      
  39:  }
  40:   
  41:   
  42:  int main()
  43:  {
  44:      /*数组元素从0开始存放*/
  45:      int A[] = {0,5,6,7,-3,555,88};
  46:      int i;
  47:      bubblesort<int>(A,6);
  48:      for(i=1; i<=6;i++)
  49:          printf("%d\n",A[i]);
  50:   
  51:      return 0;
  52:  }
posted @ 2012-04-15 20:51  justinzhang  阅读(271)  评论(0编辑  收藏  举报