使用c++的模板函數(shù)庫(kù)中的庫(kù)函數(shù),外加自己書(shū)寫(xiě)的輔助函數(shù)進(jìn)行選擇排序的測(cè)試。
可以自己創(chuàng)建一個(gè).h文件掸犬,文件中書(shū)寫(xiě)自己可能用的到的方法珊楼,在此我書(shū)寫(xiě)了一個(gè)結(jié)構(gòu)體函數(shù)通殃,和輸出函數(shù)的.h文件,來(lái)幫助我完成selectionSort函數(shù)的測(cè)試厕宗。
//student.h file
//宏定義 為了解決.h文件的多重引用問(wèn)題
#ifndef SELECTIONSORT_SORTTESTHELPER_H
#define SELECTIONSORT_SORTTESTHELPER_H
#include <iostream>
#include <string>
using namespace std;
namespace student{
struct Student{
string name;
int score;
bool operator< (const Student &otherStudent) {
// return score < otherStudent.score;//分?jǐn)?shù)按照從小到大進(jìn)行比較
// return score > otherStudent.score;//分?jǐn)?shù)按照從大到小進(jìn)行比較
//比較兩個(gè)學(xué)生的成績(jī)是否相同画舌,不相同的話按照分?jǐn)?shù)從大到校排序,否則的話按照名稱的Ascii順序進(jìn)行排序
return score != otherStudent.score ? score > otherStudent.score :
name < otherStudent.name;
}
friend ostream& operator<<(ostream &os,const Student &student)
{
os << "Student:" << student.name << " " <<student.score << endl;
return os;
}
};
template<typename T>
void printArr(T arr[],int n){
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return;
}
}
#endif //SELECTIONSORT_SORTTESTHELPER_H
//test driver program
#include <iostream> //cin已慢,cout
#include <algorithm> //swap
#include "student.h"http://自定義.h文件
using namespace std;
template <typename T> //泛型曲聂,是函數(shù)更通用
void selectionSort(T a[],int n)
{//尋找[i,n)區(qū)間里的最小值
int minIndex;
for(int i = 0; i < n-1; i++){
minIndex = i;
for(int j = i + 1; j < n; j++){
if(a[j] < a[minIndex])
minIndex = j;
}
swap(a[i],a[minIndex]); //swap the numbers
}
}
int main()
{
//test integer
int arr[10] = {10,9,8,7,6,5,4,3,2,1};
selectionSort(arr,10);
student::printArr(arr,10);//print out the elements of the array
//test float
float b[4] = {4.4,3.3,2.2,1.1};
selectionSort(b,4);
student::printArr(b,4);//print out the elements of the array
//test string
string c[4] = {"D","C","B","A"};
selectionSort(c,4);
student::printArr(c,4);//print out the elements of the array
//test self defination
student::Student d[4] = {{"D",90},{"C",100},{"B",95},{"A",95}};//Reference the structment through student.h
selectionSort(d,4);
student::printArr(d,4); //Reference to print out
return 0;
}
You can leave me a message if you find out any mistake in my diary, I'll correct it, thanks.