C++ 使用模板实现冒泡排序


不说废话,直接上代码。。。

运行截图:

C++ 使用模板实现冒泡排序

// Sort.h

#pragma once
#include<iostream>
#include<string>
using namespace std;

class Sort
{
public:
 Sort(void);
 ~Sort(void);

 template<typename T>
 static void print(T *array,const int size)
 {
  if(NULL==array)
   throw;

  if(0>=size)
   return;
 
  for(int i=0;i<size;++i)
   cout<<array[i]<<" ";
  cout<<endl;
 }

 template<typename T>
 static void bubble_sort_up(T *array,const int size)
 {
  if(NULL==array)
   throw;
 
  if(0>=size)
   return;

  for(int i=0;i<size-1;++i)
  {
   for(int j=0;j<size-i-1;++j)
   {
    if(array[j]>array[j+1])
    {
    // array[j]=array[j]+array[j+1]-(array[j+1]=array[j]);
     T temp=array[j];
     array[j]=array[j+1];
     array[j+1]=temp;
    }
   }
  }
 }

 template<typename T>
 static void bubble_sort_down(T *array,const int size)
 {
  if(NULL==array)
   throw;
 
  if(0>=size)
   return;

  for(int i=0;i<size-1;++i)
  {
   for(int j=0;j<size-i-1;++j)
   {
    if(array[j]<array[j+1])
    {
    // array[j]=array[j]+array[j+1]-(array[j+1]=array[j]);
     T temp=array[j];
     array[j]=array[j+1];
     array[j+1]=temp;
    }
   }
  }
 }
};

 

// Sort.cpp

#include "StdAfx.h"
#include "Sort.h"
#include<iostream>
#include<string>
using namespace std;

Sort::Sort(void)
{
}

Sort::~Sort(void)
{
}

int _tmain(int argc, _TCHAR* argv[])
{
 int a[]={4, 1, 2, 5, 3};
 const int size_a=sizeof(a)/sizeof(a[0]);

 double b[]={1.11111, 3.33333, 2.22222};
 const int size_b=sizeof(b)/sizeof(b[0]);

 char c[]="CDmnopEFGhijABklq";
 const int size_c=strlen(c);

 string d[]={"bbb","aaa","ccc","ddd"};
 const int size_d=sizeof(d)/sizeof(d[0]);

 cout<<"原始数据"<<endl;
 Sort::print(a,size_a);
 Sort::print(b,size_b);
 Sort::print(c,size_c);
 Sort::print(d,size_d);

 Sort::bubble_sort_up(a,size_a);
 Sort::bubble_sort_up(b,size_b);
 Sort::bubble_sort_up(c,size_c);
 Sort::bubble_sort_up(d,size_d);

 cout<<endl<<"经冒泡排序升序排序后"<<endl;
 Sort::print(a,size_a);
 Sort::print(b,size_b);
 Sort::print(c,size_c);
 Sort::print(d,size_d);

 Sort::bubble_sort_down(a,size_a);
 Sort::bubble_sort_down(b,size_b);
 Sort::bubble_sort_down(c,size_c);
 Sort::bubble_sort_down(d,size_d);

 cout<<endl<<"经冒泡排序降序排序后"<<endl;
 Sort::print(a,size_a);
 Sort::print(b,size_b);
 Sort::print(c,size_c);
 Sort::print(d,size_d);

 return 0;
}

相关内容