程序主体main.cpp
#include <iostream>
#include "Student.h"
#include "SortTestHelper.h"
using namespace std;
template<typename T>
void selectionSort(T arr[], int n) {
for (int i = 0; i < n; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
swap(arr[i], arr[minIndex]);
}
}
}
int main() {
int n = 100;
int *arr = SortTestHelper::generateRandomArray(n, 0, 100);
SortTestHelper::testSort("选择排序", selectionSort, arr, n);
delete[] arr;
return 0;
}
自定义结构体-Student.h
#ifndef TEST_STUDENT_H
#define TEST_STUDENT_H
#include<iostream>
#include <string>
using namespace std;
struct Student {
string name;
int score;
bool operator<(const Student &otherStudent) {
return score < otherStudent.score;
}
friend ostream &operator<<(ostream &os, const Student &student) {
os << "name: " << student.name << " score: " << student.score << endl;
return os;
}
};
#endif
SortTestHelper.h
#ifndef TEST_SORTTESTHELPER_H
#define TEST_SORTTESTHELPER_H
#include <iostream>
#include <cassert>
#include <ctime>
#include <string>
using namespace std;
namespace SortTestHelper {
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;
}
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(const string &sortName, void (*sort)(T [], int), T arr[], int n) {
clock_t startTime = clock();
sort(arr, n);
clock_t endTime = clock();
printArray(arr, n);
cout << startTime << " " << endTime;
assert(isSorted(arr, n));
cout << sortName << " : " << double(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
}
}
#endif