歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++ 使用模板實現冒泡排序

C++ 使用模板實現冒泡排序

日期:2017/3/1 9:48:24   编辑:Linux編程

不說廢話,直接上代碼。。。

運行截圖:

// 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;
}

Copyright © Linux教程網 All Rights Reserved