选择排序的函数模板,关于比较大小的运算符的重载,以及样例示范。
代码如下:
#include <bits/stdc++.h> using namespace std; template <typename T> void selectionSort(T arr[], int n){//选择排序从小到大排序,o^2时间复杂度 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 ] ) ; } } struct Student{ string name; int score; bool operator<(const Student &otherStudent ){ // return score < otherStudent.score ;//成绩由低到高排序,姓名按原始顺序 return score != otherStudent.score ? score > otherStudent.score : name < otherStudent.name ; //先是成绩由高到低排序,然后在string类型的姓名也从低到高排序;故可知运算符用户自定义重载以后,完全可以改变“大小”的含义,大小都是相应的,是由用户定义的. } friend ostream& operator<<(ostream &os, const Student &student ){ os<<"Student: "<< student.name <<" "<<student.score << endl; return os ; } }; int main(){ // 测试模板函数,传入整型数组 int a[] = { 8, 7, 6, 5, 10, 9, 4, 3, 2, 1 }; int n_a = sizeof(a)/sizeof(a[0]); cout<<"n_a = "<<n_a<<endl; selectionSort( a , n_a ); for( int i = 0 ; i < n_a ; i ++ ) cout<<a[i]<<" "; cout<<endl; // 测试模板函数,传入浮点数数组 float b[] = { 2.2, 4.4, 3.3, 1.1 }; int n_b = sizeof(b)/sizeof(b[0]); cout<<"n_b = "<<n_b<<endl; selectionSort(b, n_b ); for( int i = 0 ; i < n_b ; i ++ ) cout<<b[i]<<" "; cout<<endl; // 测试模板函数,传入字符串数组 string c[] = { "C" ,"D","B","A"}; int n_c = sizeof(c)/sizeof(c[0]); cout<<"n_c = "<<n_c<<endl; selectionSort(c, n_c ); for( int i = 0 ; i < n_c ; i ++ ) cout<<c[i]<<" "; cout<<endl; // 测试模板函数,传入自定义结构体Student数组 Student d[] = { {"B",95} , {"D",90} , {"C",100} , {"A",95} }; int n_d = sizeof(d)/sizeof(d[0]) ; cout<<"n_d = "<<n_d<<endl; selectionSort(d, n_d ); for( int i = 0 ; i < n_d ; i ++ ) cout<<d[i]; cout<<endl; return 0 ; }
当然了,真正到了算法排序代码里,是不会使用时间复杂度为0^2的选择排序的,,,此处只是作为样例而存在的。