forked from Jdroida/free_learning
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortTestHelper.h
More file actions
59 lines (58 loc) · 1.32 KB
/
SortTestHelper.h
File metadata and controls
59 lines (58 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#ifndef SELECTIONSORT_SORTTESTHELPER_H
#define SELECTIONSORT_SORTTESTHELPER_H
#include<iostream>
#include<ctime>
#include<cassert>
using namespace std;
namespace SortTestHelper{
//生成有n个元素的随机数组 e范围是l到r之间
int* generateRandomArray(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;
}
int* generateNearlyOrderedArray(int n,int swapTimes){
int *arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=i;
srand(time(NULL));
for(int i=0;i<swapTimes;i++){
int posx=rand()%n;
int posy=rand()%n;
swap(arr[posx],arr[posy]);
}
return arr;
}
template<typename T>
void printArray(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 testSort(string sortName,void(*sort)(T[],int),T arr[],int n){
clock_t startTime=clock();
sort(arr,n);
clock_t endTime=clock();
assert(isSorted(arr,n));
cout<<sortName<<":"<<double(endTime-startTime)/CLOCKS_PER_SEC<<"s"<<endl;
}
int* copyIntArray(int a[],int n){
int* arr=new int[n];
copy(a,a+n,arr);
return arr;
}
}
#endif