您的位置:首页 > 其它

用模板写选择排序-数组

2014-09-06 15:39 134 查看
今天,我们一起来写选择排序,主要是熟悉模板编程,具体如例1所示。

例1 选择排序-数组

SelectSort.hpp内容:

#ifndef _SELECT_SORT_H_
#define _SELECT_SORT_H_
template<typename T>
bool SelectSort(T * pInput, int nLen)
{
int i = 0;
int j = 0;
int nMin = 0;
T tTemp;
if (!pInput)
return false;
for (i = 0; i < nLen; i++)
{
nMin = i;
for (j = i + 1; j < nLen; j++)
{
if (pInput[j] < pInput[nMin])
{
nMin = j;
}
}
if (nMin != i)
{
tTemp = pInput[i];
pInput[i] = pInput[nMin];
pInput[nMin] = tTemp;
}
}
return true;
}
#endif
main.cpp的内容:

#include "SelectSort.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 (SelectSort<int>(a, 1) == false)
{
cout << "排序失败." << endl;
}
else
{
cout << "排序后:" << endl;
for (i = 0; i < 10; i++)
{
cout << a[i] << '\t';
}
}
system("pause");
return;
}
运行效果如图1所示:



图1 运行效果

今天,我们一起完成了选择排序,希望对家回去实践一下,加深体会。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: