您的位置:首页 > 编程语言 > C语言/C++

利用c++模板实现冒泡排序

2015-05-14 22:54 706 查看
/* ArrayBubbleSort.hpp */

#ifndef _ARRAY_BUBBLE_SORT_H_
#define _ARRAY_BUBBLE_SORT_H_

template<typename T>
bool BubbleSort(T *pInput, int nLen)
{
int i = 0;
int j = 0;
bool bChange = false;
T tTemp;
if(!pInput)
{
return false;
}
for(i=0; i<nLen-1; i++)
{
bChange = false;
for(j=0; j<nLen-1-i; j++)
{
if(pInput[j]>pInput[j+1])
{
tTemp = pInput[j+1];
pInput[j+1] = pInput[j];
pInput[j] = tTemp;
bChange = true;
}
}
if(!bChange)
{
break;
}
}
return true;
}

#endif

/* BubbleSort.cpp */

#include "ArrayBubbleSort.hpp"
#include <iostream>
using namespace std;

int main()
{
int a[10] = {1,4,7,2,5,8,3,6,9,0};
int i = 0;

if(BubbleSort<int>(a,10)==false)
{
cout<<"排序失败"<<endl;
}
for(i=0; i<10; i++)
{
cout<<a[i]<<"\t";
}
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++模板 冒泡排序