# 4.代码

## SelectionSort.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[minIndex],arr[i]);//把a，b交换位置
}
}

int main() {
int arr[5] = {1,20,8,4,3};
selectionSort(arr,5);
for(int i = 0;i<5;i++){
cout << arr[i] << " "; //循环打印int数组中的元素
}
cout << endl;

float b[5] = {1.1,5.3,4.2,0.3,2.5};
selectionSort(b,5);
for(int i = 0;i<5;i++){
cout << b[i] << " "; //循环打印float数组中的元素
}
cout << endl;

string c[5] = {"A","D","B","C","E"};
selectionSort(c,5);
for(int i = 0;i<5;i++){
cout << c[i] << " "; //循环打印string数组中的元素
}
cout << endl;

Student s[5] = {{"A",50},{"D",60},{"B",30},{"E",90},{"C",60}};
selectionSort(s,5);

for(int i = 0;i<5;i++){
cout << s[i] << " ";//循环打印自定义数组中的元素
}
cout << endl;

return 0;
}

## Student.h

#ifndef STUDENT_H_
#define STUDENT_H_

#include <iostream>
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<<",";
return os;
}

};

#endif /* STUDENT_H_ */