今天,我们一起来写选择排序,主要是熟悉模板编程,具体如例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;
}
#endifmain.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] << ' ';
}
cout << endl;
if (SelectSort<int>(a, 1) == false)
{
cout << "排序失败." << endl;
}
else
{
cout << "排序后:" << endl;
for (i = 0; i < 10; i++)
{
cout << a[i] << ' ';
}
}
system("pause");
return;
}运行效果如图1所示:图1 运行效果
今天,我们一起完成了选择排序,希望对家回去实践一下,加深体会。