main.cpp
1 #include <iostream> 2 3 #include "SortTestHelper.h" 4 5 using namespace std; 6 7 template<typename T> 8 void selectionSort(T arr[],int n){ 9 for(int i = 0 ; i < n ; i ++){ 10 int minIndex = i; 11 for( int j = i + 1 ; j < n ; j ++ ) 12 if( arr[j] < arr[minIndex] ) 13 minIndex = j; 14 swap( arr[i] , arr[minIndex] ); 15 } 16 } 17 18 int main(){ 19 int n = 100000; 20 int *arr = SortTestHelper::generateRandomArray(n,0,n); 21 //selectionSort(arr,n); 22 //SortTestHelper::printArray(arr,n); 23 SortTestHelper::testSort("Selection Sort",selectionSort,arr,n); 24 delete[] arr; 25 return 0; 26 }
SortTestHelper.h
1 #include <iostream> 2 #include <ctime> 3 #include <cassert> 4 #include <string> 5 6 using namespace std; 7 8 namespace SortTestHelper{ 9 int *generateRandomArray(int n,int rangeL,int rangeR){ 10 assert(rangeL <= rangeR); 11 int *arr = new int[n]; 12 srand(time(NULL)); 13 for(int i = 0 ; i < n ; i++) 14 arr[i] = rand()%(rangeR-rangeL+1) + rangeL; 15 return arr; 16 } 17 18 template<typename T> 19 void printArray(T arr[],int n){ 20 for(int i = 0;i<n;i++) 21 cout << arr[i] <<" "; 22 cout << endl; 23 return; 24 } 25 26 template<typename T> 27 bool isSorted(T arr[],int n){ 28 for(int i = 0 ; i<n-1 ; i++) 29 if(arr[i] > arr[i+1]) 30 return false; 31 return true; 32 } 33 template<typename T> 34 void testSort(const string &sortName,void (*sort)(T[],int),T arr[],int n){ 35 36 clock_t startTime = clock(); 37 sort(arr,n); 38 clock_t endTime = clock(); 39 40 assert(isSorted(arr,n)); 41 cout << sortName << " : " << double(endTime-startTime)/CLOCKS_PER_SEC << " s" <<endl; 42 43 return; 44 } 45 }
结果:
原文:https://www.cnblogs.com/cxc1357/p/12099697.html