目标:选择排序算法
编译工具:Clion2019.3.2
代码展示:
Student.h
//
// Created by Administrator on 2019/12/21 0021.
//
#ifndef C_WORKSPACE_STUDENT_H
#define C_WORKSPACE_STUDENT_H
#include <iostream>
#include <string>
using namespace std;
struct Student{
string name;
int score;
bool operator<(const Student &otherStudent){
//return score < otherStudent.score;升序
//降序
return score > otherStudent.score;
}
friend ostream&operator<<(ostream &os, const Student &student){
os<<"Student: "<<student.name<<" "<<student.score<<endl;
return os;
}
};
#endif //C_WORKSPACE_STUDENT_H
SortTestHelper.h
//
// Created by Administrator on 2019/12/21 0021.
//
#ifndef C_WORKSPACE_SORTTESTHELPER_H
#define C_WORKSPACE_SORTTESTHELPER_H
#include <iostream>
#include <ctime>
#include <cassert>
using namespace std;
namespace SortTestHelper {
//生成有n个元素的随机数组,每个元素的随机范围为[rangeL,rangeR]
int* generateRandomArray(int n, int rangeL,int rangeR){
//让rangeL <= rangeR
assert(rangeL<=rangeR);
int *arr = new int[n];
srand(time(NULL));
for (int i = 0; i < n; ++i) {
//rand 随机一个整数
//%之后表示:范围在(rangeR-rangeL+1)+rangeL,前壁后壁
arr[i] = rand() % (rangeR-rangeL+1)+rangeL;
}
return arr;
}
template<typename T>
void printArray(T arr[], int n){
for (int i = 0; i < n; ++i) {
cout <<arr[i] <<" ";
cout <<endl;
return;
}
}
};
#endif //C_WORKSPACE_SORTTESTHELPER_H
SortTestHelper.cpp
//
// Created by Administrator on 2019/12/21 0021.
//
#include "SortTestHelper.h"
#include <iostream>
//引入自己的库
#include "Student.h"
using namespace std;
template <typename T>
void selectionSort(T arr[], int n){
for(int i = 0 ; i < n ; i ++){
// [i, n)???????
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() {
//Student 自定义类型排序
Student d[4]={ {"A",50},{"C",71},{"B",33},{"D",100} };
selectionSort(d,4);
for (int s = 0; s <= 4; ++s) {
cout<<d[s]<<" ";
cout<<endl;
}
//浮点型排序
float a[10] ={1.1,2.3,4.5,5.5,6.6,8.6};
selectionSort(a,6);
for (int j = 0; j < 6; ++j) {
cout<< a[j]<<" ";
//endl
cout<<endl;
}
//字符串排序
string c[4]={"A","C","B","D"};
selectionSort(c,4);
for (int k = 0; k <= 4; ++k) {
cout<<c[k]<<" ";
cout<<endl;
}
}