#include<iostream>
#include<algorithm>
using namespace std;
//泛型模板函数
template<typename T>
//排序输入参数:一个数组无论类型,一个数组容量大小。排序时使用下标的方式
void selectSort(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] = { 5,1,2,6,3,4,7,9,8,0 };
selectSort(a,10);
for (int i = 0; i < 10; i++) {
cout << a[i] << endl;
}
//对浮点类型数组进行排序
float b[4] = {1.1,6.1,2.3,3.1};
selectSort(b, 4);
for (int i = 0; i < 4; i++)
cout << b[i] << endl;
//对字符进行排序
string k[3] = {"abc","aac","d"};
selectSort(k,3);
for (int i = 0; i < 3; i++)
cout << k[i] << endl;
return 0;
}
运算符重载方式
新建Student.h
#ifndef SELSETIONSORT_STUDENT_H
#define SELSETIONSORT_STUDENT_H
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int score;
bool operator<(const Student & otherStudent) {
return score > otherStudent.score;
}
friend ostream& operator<<(ostream& os, const Student& student) {
os << "student:" << student.name << " " << student.score << endl;
return os;
}
};
#endif
.c代码:
#include<iostream>
#include<algorithm>
#include"Student.h"
using namespace std;
//泛型模板函数
template<typename T>
//排序输入参数:一个数组无论类型,一个数组容量大小。排序时使用下标的方式
void selectSort(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] = { 5,1,2,6,3,4,7,9,8,0 };
selectSort(a,10);
for (int i = 0; i < 10; i++) {
cout << a[i] << endl;
}
//对浮点类型数组进行排序
float b[4] = {1.1,6.1,2.3,3.1};
selectSort(b, 4);
for (int i = 0; i < 4; i++)
cout << b[i] << endl;
//对字符进行排序
string k[3] = {"abc","aac","d"};
selectSort(k,3);
for (int i = 0; i < 3; i++)
cout << k[i] << endl;
//结构体
Student d[3] = { {"A",90},{"b",10},{"c",30}, };
selectSort(d, 3);
for (int i = 0; i < 3; i++)
cout << d[i] << endl;
return 0;
}
运行结果: