网站运营者网址/百度电话人工服务
上一节中的排序算法只能对整型数组进行排序
下面用函数模板进行改进:
#include <iostream>
#include "student.h"using namespace std;
//参数为数组和数组中元素的个数
template<class T>
void selectionSort(T a[],int n)
{int i=0;int minIndex=0;for(i=0;i<n;i++){ //寻找[i,n)区间里的最小值minIndex=i; //minIndex表示当前最小值所在的位置for(int j=i+1;j<n;j++){if(a[j]<a[minIndex]){minIndex=j;}}if(i!=minIndex){swap(a[i],a[minIndex]);}}
}int main()
{int i=0;//int 型数组int b[5]={1,3,4,2,5};selectionSort(b,5);for(i=0;i<4;i++){cout<<b[i]<<' ';}cout<<b[i]<<endl;//float型float c[5]={1.1,2.2,1.11,3.3,4.4};selectionSort(c,5);for(i=0;i<4;i++){cout<<c[i]<<' ';}cout<<c[i]<<endl;//string型string d[5]={"a","d","c","e","a"};selectionSort(d,5);for(i=0;i<4;i++){cout<<d[i]<<' ';}cout<<d[i]<<endl;//student型student s[5]={{"a",98},{"d",100},{"c",90},{"e",88},{"b",100}};selectionSort(s,5);for(i=0;i<4;i++){cout<<s[i];}cout<<s[i]<<endl;return 0;
}
student.h:
using namespace std;
struct student{string name;int score;student(string n,int s):name(n),score(s){}bool operator<(const student& other){return score<other.score;}friend ostream & operator<<(ostream & out,const student& other){out<<other.name<<" "<<other.score<<endl;return out;}
};