排序基础
选择排序法-Selection Sort
#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++) {
//寻找[i,n]区间的最小值
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 a[10] = {1, 3, 8, 7, 6, 5, 4, 3, 2, 1};
int n = 10000;
int *arr = SortTestHelper::generateRandomArray(n, 0, n);
selectionSort(arr, n);
SortTestHelper::printArray(arr, n);
delete[] arr;
// for (int i = 0; i < n; i++)
// cout << arr[i] << " ";
// cout << endl;
float b[5] = {1.2, 3.4, 8.5, 7.9, 6.3};
selectionSort(b, 5);
for (int i = 0; i < 5; i++)
cout << b[i] << " ";
cout << endl;
string c[5] = {"F",
"D",
"E",
"A",
"B"};
selectionSort(c, 5);
for (int i = 0; i < 5; i++)
cout << c[i] << " ";
cout << endl;
Student d[] = {{"D", 90},
{"C", 100},
{"B", 80},
{"A", 80}};
selectionSort(d, 4);
for (int i = 0; i < 4; i++)
cout << d[i] << " ";
cout << endl;
return 0;
}
随机生成算法测试用例
#ifndef ALGORITHMS_SORTTESTHELPER_H
#define ALGORITHMS_SORTTESTHELPER_H
#include <iostream>
#include <cassert>
using namespace std;
namespace SortTestHelper {
//生产有 n 个元素的随机数组,每个元素的范围为[rangL,rangR]
int *generateRandomArray(int n, int rangL, int rangR) {
assert(rangL <= rangR);
int *arr = new int[n];
srand(time(NULL));
for (int i = 0; i < n; i++)
arr[i] = rand() % (rangL - rangR + 1) + rangL;
return arr;
}
template<typename T>
void printArray(T arr[], int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return;
}
}
endif //ALGORITHMS_SORTTESTHELPER_H
测试算法的性能
衡量一个算法性能的最简单的方式就是看其在特定的数据集上的执行时间。对此,我们在上面的SortTestHelper.h
文件中新增一个函数。
templete<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();
cout << sortName << ":" << double(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
return;
}