使用c++的模板函數(shù)庫中的庫函數(shù),外加自己書寫的輔助函數(shù)進(jìn)行選擇排序的測(cè)試。
可以自己創(chuàng)建一個(gè).h文件,文件中書寫自己可能用的到的方法,在此我書寫了隨機(jī)產(chǎn)生0~10000之間隨機(jī)數(shù)和打印輸出的模板函數(shù)的.h文件,來幫助我完成selectionSort函數(shù)的測(cè)試。
//SortTestHelper.h file
//宏定義
#ifndef SELECTIONSORT_SORTTESTHELPER_H
#define SELECTIONSORT_SORTTESTHELPER_H
#include <iostream>
#include <ctime>
#include <cassert>
using namespace std;
namespace SortTestHelper{
//生成有n個(gè)元素的隨機(jī)數(shù)組,每個(gè)元素的隨機(jī)范圍為[rangeL,rangeR]
int* generateRandomArray(int n,int rangeL,int rangeR){
assert(rangeL <= rangeR);//保證左邊界值小于右邊界值的庫函數(shù)
int *arr = new int[n];
srand(time(NULL)); //隨機(jī)種子的設(shè)置
for(int i = 0; i < n; i++){
arr[i] = rand() % (rangeR - rangeL + 1) + rangeL; //為數(shù)組元素使用隨機(jī)數(shù)賦值
}
return arr;//返回函數(shù)名
}
template<typename T>//輸出模板函數(shù)
void printArr(T arr[],int n){
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return;
}
}
#endif //SELECTIONSORT_SORTTESTHELPER_H
//test program the
#include <iostream>
#include "SortTestHelper.h" //reference the file of .h
using namespace std;
void swap(int *xp,int *yp) //a fuction to swap the numbers
{
int tmp;
tmp = *xp;
*xp = *yp;
*yp = tmp;
}
void selectionSort(int a[],int n)// the function to the selectionSort
{//尋找[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]) //find the minimum of the unsort array
minIndex = j;
}
swap(&a[i],&a[minIndex]); //swap the numbers
}
}
//driver program
int main()
{
int n = 10000;
int *arr = SortTestHelper::generateRandomArray(n,0,n); //reference the file of .h
selectionSort(arr,n);//selectionSort to sort the array
SortTestHelper::printArr(arr,n);//print out the elements of the array
delete[] arr; //free the space that was ever distributed to the array
return 0;
}
You can leave me a message if you find out any mistake in my diary, I'll correct it, thanks.