设为首页 加入收藏

TOP

C++ 使用模板实现冒泡排序
2014-11-24 01:19:57 来源: 作者: 【 】 浏览:4
Tags:使用 模板 实现 冒泡 排序

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


运行截图:


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


// Sort.h


#pragma once
#include
#include
using namespace std;


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


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


if(0>=size)
return;

for(int i=0;i cout< cout< }


template
static void bubble_sort_up(T *array,const int size)
{
if(NULL==array)
throw;

if(0>=size)
return;


for(int i=0;i {
for(int j=0;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
static void bubble_sort_down(T *array,const int size)
{
if(NULL==array)
throw;

if(0>=size)
return;


for(int i=0;i {
for(int j=0;j {
if(array[j] {
// 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
#include
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<<"原始数据"< 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< 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< Sort::print(a,size_a);
Sort::print(b,size_b);
Sort::print(c,size_c);
Sort::print(d,size_d);


return 0;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Linux外部中断架构初始化流程----.. 下一篇C++中函数指针和函数对象的区别与..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: