#include <iostream>
#include <string>
#include <vector>
using namespace std;
template<typename T>
class Sorter {
public:
enum Algorithm {
BUBBLE_SORT,
SELECTION_SORT,
INSERTION_SORT
};
void sort(vector<T>& arr, Algorithm algorithm = BUBBLE_SORT) {
switch (algorithm) {
case BUBBLE_SORT:
bubbleSort(arr);
break;
case SELECTION_SORT:
selectionSort(arr);
break;
case INSERTION_SORT:
insertionSort(arr);
break;
}
}
private:
void bubbleSort(vector<T>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr[j], arr[j + 1]);
}
}
}
}
void selectionSort(vector<T>& arr) {
int n = arr.size();
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (i != minIndex) {
swap(arr[i], arr[minIndex]);
}
}
}
void insertionSort(vector<T>& arr) {
int n = arr.size();
for (int i = 1; i < n; i++) {
T key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
};
class Student {
public:
Student(const string& name = "", int score = 0) : m_Name(name), m_Score(score) {}
string getName() const { return m_Name; }
int getScore() const { return m_Score; }
bool operator>(const Student& other) const {
return m_Score > other.m_Score;
}
bool operator<(const Student& other) const {
return m_Score < other.m_Score;
}
friend ostream& operator<<(ostream& os, const Student& student) {
os << "Name: " << student.m_Name << ", Score: " << student.m_Score;
return os;
}
private:
string m_Name;
int m_Score;
};
int main() {
vector<Student> students = { Student("Alice", 80), Student("Bob", 60), Student("Charlie", 70) };
Sorter<Student> sorter;
sorter.sort(students, Sorter<Student>::BUBBLE_SORT);
for (const auto& student : students) {
cout << student << endl;
}
return 0;
}
基于C++类模板编写一个排序类,至少实现三种排序算法,并用这个排序类对学生数组进行排序,学生类包含姓名、成绩等属性及对应的读写方法、运算符。
最新推荐文章于 2023-10-26 15:00:18 发布