算法与数据结构
来源:互联网 发布:java图形用户界面 编辑:程序博客网 时间:2024/06/06 18:37
排序基础
选择排序法-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; }
阅读全文
0 0
- 数据结构与算法 -- 算法
- 【数据结构与算法】浅谈数据结构与算法
- 【数据结构与算法】【Some】数据结构与算法
- 数据结构笔记-----数据结构与算法
- 【数据结构与算法】数据结构备忘
- 数据结构与算法总论
- 数据结构与算法总论
- 数据结构与算法基础
- 数据结构与算法总论
- 数据结构与算法
- 数据结构与算法基础
- 数据结构与算法笔记
- 数据结构与算法
- 数据结构与算法
- 数据结构与算法
- 算法与数据结构简介
- 数据结构与算法
- 数据结构与算法(1)
- 编程理解——翻转前k个字符
- JSP页面调用接口发送JSON格式数据
- JAVA Freemarker(6)--自定义指令
- Git--将已有的项目添加到github
- hihocoder 1591
- 算法与数据结构
- 开发中遇到的hibernate异常:a different object with the same identifier value was already associated with the
- BZOJ1500: [NOI2005]维修数列(平衡树)
- 12.笔记go语言——垃圾回收
- Headshot UVA
- 【广告算法工程师入门 10】机制设计-不完全信息博弈与拍卖
- 剑指offer---java练习篇(3)
- Bing it UVALive
- dubbo admin配置