#include <iostream>
#include "testhelper.h"
using namespace std;
//参数为数组和数组中元素的个数
template<class T>
void selectionSort(T a[],int n)
{
int i=0;
int minIndex=0;
for(i=0;i<n;i++)
{ //寻找[i,n)区间里的最小值
minIndex=i; //minIndex表示当前最小值所在的位置
for(int j=i+1;j<n;j++)
{
if(a[j]<a[minIndex])
{
minIndex=j;
}
}
if(i!=minIndex)
{
swap(a[i],a[minIndex]);
}
}
}
int main()
{
int n=100000;
int *b=testhelper::gen_array(n,1,100);
//selectionSort(b,n);
//testhelper::printarr(b,n);
testhelper::sorttest("selection sort",selectionSort,b,n);
delete[] b;
return 0;
}
testhelper.h:
#ifndef TESTHELPER_H_INCLUDED
#define TESTHELPER_H_INCLUDED
#include <iostream>
#include <ctime>
#include <cassert>
using namespace std;
namespace testhelper
{
//生成有n个元素的随机数组,每个元素的随机范围为[rangeL,rangeR]
int *gen_array(int n,int rangeL,int rangeR)
{
assert(rangeL<=rangeR);
int *arr=new int[n];
srand(time(NULL));
for(int i=0;i<n;i++)
{
arr[i]=rand()%(rangeR-rangeL+1)+rangeL;
}
return arr;
}
//函数模板,打印数组中元素
template<typename T>
void printarr(T * arr,int n)
{
for(int i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;
}
//判断数组是否有序
template<typename T>
bool issorted(T arr[],int n)
{
for(int i=0;i<n-1;i++)
{
if(arr[i]>arr[i+1])
return false;
}
return true;
}
//测试排序算法的时间
template<typename T>
void sorttest(string sortname,void (*sort)(T[],int),T arr[],int n)
{
clock_t begins=clock();
sort(arr,n);
clock_t ends=clock();
assert(issorted(arr,n));
cout<<sortname<<":"<<double(ends-begins) /CLOCKS_PER_SEC <<"s"<<endl;
return ;
}
}
#endif // TESTHELPER_H_INCLUDED