很多情況下,我們需要對我們所寫的排序算法的性能進(jìn)行一個統(tǒng)計測試镊叁,該測試用例就是用來實(shí)現(xiàn)該功能唾琼。在之前的基礎(chǔ)上增加了testSort函數(shù),用來測試所用使時間疯趟,增加了isSorted函數(shù)測試函數(shù)的正確性拘哨。詳細(xì)測試如下:
//test sortTestHelper1.h
//宏定義
#ifndef SELECTIONSORT_SORTTESTHELPER_H
#define SELECTIONSORT_SORTTESTHELPER_H
#endif
#include <iostream>
#include <ctime>
#include <cassert>
using namespace std;
namespace SortTestHelper1{
//生成有n個元素的隨機(jī)數(shù)組,每個元素的隨機(jī)范圍為[rangeL,rangeR]
int* generateRandomArray(int n,int rangeL,int rangeR){
assert(rangeL <= rangeR); //若左邊界小于右邊界信峻,終止程序
int *arr = new int[n]; //動態(tài)數(shù)組的生成
srand(time(NULL)); //定義隨機(jī)種子
for(int i = 0; i < n; i++){
arr[i] = rand() % (rangeR - rangeL + 1) + rangeL;//為每一個數(shù)組元素使用隨機(jī)數(shù)進(jìn)行賦值
}
return arr;//將產(chǎn)生的隨機(jī)數(shù)數(shù)組的首地址進(jìn)行返回
}
template<typename T>
void printArr(T arr[],int n){ //輸出模板函數(shù)
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return;
}
template <typename T>
bool isSorted(T arr[],int n) //測試函數(shù)執(zhí)行的正確性倦青,該處測試選擇排序算法的正確性
{
for(int i = 0; i < n - 1; i++)//注意邊界問題
if(arr[i] > arr[i+1]) //如果前一個元素都小于后一個元素的值,則證明函數(shù)運(yùn)行的正確盹舞,返回值為true
return false;
return true;
}
template <typename T>//定義泛型
void testSort(string sortName, void(*sort)(T[],int),T arr[],int n)
{
clock_t startTime = clock();//定義一個變量存儲存儲開始時鐘周期
sort(arr,n); //執(zhí)行sort函數(shù)
clock_t endTime = clock(); // 定義一個變量存儲存儲結(jié)束時鐘周期
assert(isSorted(arr,n)); //查看運(yùn)行結(jié)果是否出錯产镐,若出錯,則終止程序運(yùn)行
//計算總的周期數(shù)/每秒鐘的始終周期數(shù)得到總的測試秒數(shù)踢步,并輸出
cout << sortName << " : " << (double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
return;//函數(shù)無返回值
}
}
#include <iostream>
#include <algorithm>
#include "SortTestHelper1.h"
using namespace std;
template <typename T>
void selectionSort(T a[],int n)
{//尋找[i,n)區(qū)間里的最小值
int minIndex;
for(int i = 0; i < n-1; i++){
minIndex = i;
for(int j = i + 1; j < n; j++){
if(a[j] < a[minIndex])
minIndex = j;
}
swap(a[i],a[minIndex]); //swap the numbers
}
}
int main()
{
int n = 10000;
int *arr = SortTestHelper1::generateRandomArray(n,0,n);
selectionSort(arr,n);//selectionSort to sort the array
// SortTestHelper1::printArr(arr,n);//print out the elements of the array //輸出
SortTestHelper1::testSort("Selection Sort",selectionSort,arr,n) ; //測試用例
delete[] arr;
return 0;
}