泛型编程Selection Sort 选择排序
2017-01-17 13:41
225 查看
selection sort
main.cpp#include <iostream> #include "Student.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 a[10] = {10,9,8,7,6,5,4,3,2,1}; selectionSort( a , 10 ); for( int i = 0 ; i < 10 ; i ++ ) cout<<a[i]<<" "; cout<<endl; // 测试模板函数,传入浮点数数组 float b[4] = {4.4,3.3,2.2,1.1}; selectionSort(b,4); for( int i = 0 ; i < 4 ; i ++ ) cout<<b[i]<<" "; cout<<endl; // 测试模板函数,传入字符串数组 string c[4] = {"D","C","B","A"}; selectionSort(c,4); for( int i = 0 ; i < 4 ; i ++ ) cout<<c[i]<<" "; cout<<endl; // 测试模板函数,传入自定义结构体Student数组 Student d[4] = { {"D",90} , {"C",100} , {"B",95} , {"A",95} }; selectionSort(d,4); for( int i = 0 ; i < 4 ; i ++ ) cout<<d[i]; cout<<endl; return 0; }
Student.h
// #ifndef INC_02_SELECTION_SORT_USING_TEMPLATE_STUDENT_H #define INC_02_SELECTION_SORT_USING_TEMPLATE_STUDENT_H #include <iostream> #include <string> using namespace std; 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; } }; #endif //INC_02_SELECTION_SORT_USING_TEMPLATE_STUDENT_H
相关文章推荐
- JavaScript演示排序算法
- jackson、Gson反序列化 泛型
- JAVA泛型—— 3fe8 转
- JAVA泛型详解——转
- 编写高质量代码改善C#程序――使用泛型集合代替非泛型集合(建议20)
- 简单学习C#中的泛型方法使用
- C#通过反射创建自定义泛型
- C#泛型用法实例分析
- C#的泛型方法解析
- C语言泛型编程实例教程
- 算法之排序算法的算法思想和使用场景总结
- 用C语言的泛型实现交换两个变量值
- PHP版本常用的排序算法汇总
- C# 泛型的简单理解(安全、集合、方法、约束、继承)分享
- C#泛型Dictionary的用法实例详解
- C#泛型和反射实例解析
- C#泛型实例详解
- JavaScript实现多种排序算法
- .NET开发基础:从简单的例子理解泛型 分享
- 常用Java排序算法详解