# 慢时光~

## 选择排序的实现以及性能测试

 1 #ifndef INC_03_SELECTION_SORT_DETECT_PERFORMANCE_SORTTESTHELPER_H
2 #define INC_03_SELECTION_SORT_DETECT_PERFORMANCE_SORTTESTHELPER_H
3 #include <iostream>
4 #include <ctime>
5 #include <cassert>
6 #include <string>
7 using namespace std;
8 namespace SortTestHelper {
9     // 生成有n个元素的随机数组,每个元素的随机范围为[rangeL, rangeR]
10         int *generateRandomArray(int n, int rangeL, int rangeR) {
11         assert(rangeL <= rangeR);
12         int *arr = new int[n];
13         srand(time(NULL));
14         for (int i = 0; i < n; i++)
15             arr[i] = rand() % (rangeR - rangeL + 1) + rangeL;
16         return arr;
17     }
18     // 打印arr数组的所有内容
19     template<typename T>
20     void printArray(T arr[], int n) {
21
22         for (int i = 0; i < n; i++)
23             cout << arr[i] << " ";
24         cout << endl;
25
26         return;
27     }
28     // 判断arr数组是否有序
29     template<typename T>
30     bool isSorted(T arr[], int n) {
31
32         for (int i = 0; i < n - 1; i++)
33             if (arr[i] > arr[i + 1])
34                 return false;
35
36         return true;
37     }
38     template<typename T>
39     void testSort(const string &sortName, void (*sort)(T[], int), T arr[], int n) {
40
41         clock_t startTime = clock();
42         sort(arr, n);
43         clock_t endTime = clock();
44
45         assert(isSorted(arr, n));
46         cout << sortName << " : " << double(endTime - startTime) / CLOCKS_PER_SEC << " s" << endl;
47
48         return;
49     }
50 };
51 #endif

 1 #include <iostream>
2 #include "SortTestHelper.h"
3 using namespace std;
4 template<typename T>
5 void selectionSort(T arr[], int n){
6     for(int i = 0 ; i < n ; i ++){
7         int minIndex = i;
8         for( int j = i + 1 ; j < n ; j ++ )
9             if( arr[j] < arr[minIndex] )
10                 minIndex = j;
11         swap( arr[i] , arr[minIndex] );
12     }
13 }
14 int main() {
15     int n = 20000;
16     int *arr = SortTestHelper::generateRandomArray(n,0,n);
17     SortTestHelper::testSort("Selection Sort", selectionSort, arr, n);
18     delete[] arr;
19     return 0;
20 }
21     

#### 输了不可怕，大不了从头再来，我们还年轻---周红

posted on 2018-12-05 15:24  Tom-shushu  阅读(470)  评论(0编辑  收藏  举报