Selection Sort(选择排序)
来源:互联网 发布:淘宝详情页好做吗 编辑:程序博客网 时间:2024/06/05 11:19
选择排序:从未排好的部分的第一个作为最小(最大)的,然后依次和剩余的比较,如果有更小(更大)的,记下下标,以此作为新的最小(最大)值,继续比较,一趟结束后,然后和第一个进行交换。
核心代码
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] ); }}
生成随机测试数组
namespace SortTestHelper{ // 生成有n个元素的随机数组,每个元素的随机范围为 [langeL, rangeR] 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; }}
测试代码运行时间
namespace SortTestHelper{ 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; return; }}
运算符重载
struct Student{ string name; int score; bool operator<(const Student &otherStudent){ return score != otherStudent.score ? score < otherStudent.score : name < otherStudent.name; } friend ostream& operator<<(ostream &os, const Student &student){ os<<"Student: "<<student.name<<" "<<student.score<<endl; return os; }};
阅读全文
0 0
- 选择排序(selection sort)
- 选择排序(selection sort)
- 选择排序(selection sort)
- 选择排序(Selection Sort)
- 选择排序(Selection Sort)
- 选择排序(selection sort)
- Selection Sort(选择排序)
- 选择排序(selection sort)
- 选择排序(Selection Sort)
- selection sort 选择排序
- 选择排序 Selection Sort
- 选择排序(Selection Sort)
- 选择排序(Selection Sort)
- 选择排序 (Selection Sort)
- 选择排序(Selection sort)
- 选择排序 (Selection sort)
- 选择排序Selection sort
- Selection Sort(选择排序)
- linux-文件挂载
- 1057. 数零壹
- 函数crossvalind
- nginx学习笔记(一)
- Kibana使用的lucene查询语法
- Selection Sort(选择排序)
- django channels websocket 聊天室
- SqlServer中对应的有外键的主表数据,无法truncate表的处理
- 对oracle中分组函数的一点感悟
- POJ-1284 Primitive Roots 欧拉函数
- javascript闭包传参和事件的循环绑定示例探讨
- 设计模式6——装饰模式
- 白盒测试方法
- LDAP服务器的概念和原理简单介绍