用模板写冒泡排序-数组
今天,我们一起来写一个冒泡排序,仍然使用模板。
例1 用模板写冒泡排序-数组
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;
}
#endifmain.cpp内容:#include "ArrayBubbleSort.hpp"
#include <iostream>
using namespace std;
void main()
{
int i = 0;
int a[10] = { 1, 4, 7, 2, 5, 8, 3, 6, 9, 0 };
cout << "排序前:" << endl;
for (i = 0; i < 10; i++)
{
cout << a[i] << "\t";
}
cout << endl;
if (BubbleSort<int>(a, 10) == false)
{
cout << "排序失败." << endl;
}
cout << "排序后:" << endl;
for (i = 0; i < 10; i++)
{
cout << a[i] << "\t";
}
cout << endl;
system("pause");
return;
}运行效果如图1所示:图1 运行效果
今天,我们一起完成了冒泡排序,希望大家多实践。
浙公网安备 33010602011771号