2.使用模板(泛型)編寫算法

用模板編寫選擇排序函數(shù),并分別用整型數(shù)組,浮點型數(shù)組,字符串型數(shù)組,以及自定義結構體Student型數(shù)組進行測試

main.cpp:
#include <iostream>
#include "Student.h"

using namespace std;

template<typename T>
void selectionSort(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() {

    // 測試模板函數(shù),傳入整型數(shù)組
    int a[10] = {10,9,8,7,6,5,4,3,2,1};
    selectionSort( a , 10 );
    for( int i = 0 ; i < 10 ; i ++ )
        cout<<a[i]<<" ";
    cout<<endl;

    // 測試模板函數(shù),傳入浮點數(shù)數(shù)組
    float b[4] = {4.4,3.3,2.2,1.1};
    selectionSort(b,4);
    for( int i = 0 ; i < 4 ; i ++ )
        cout<<b[i]<<" ";
    cout<<endl;

    // 測試模板函數(shù),傳入字符串數(shù)組
    string c[4] = {"D","C","B","A"};
    selectionSort(c,4);
    for( int i = 0 ; i < 4 ; i ++ )
        cout<<c[i]<<" ";
    cout<<endl;

    // 測試模板函數(shù),傳入自定義結構體Student數(shù)組
    Student d[4] = { {"D",90} , {"C",100} , {"B",95} , {"A",95} };
    selectionSort(d,4);
    for( int i = 0 ; i < 4 ; i ++ )
        cout<<d[i];
    cout<<endl;

    return 0;
}
//定義Student類型
temp.h:
#ifndef _TEMP_H
#define _TEMP_H
#include<iostream>
#include<string>
using namespace std;
struct Student{
    string name;
    int score;
//重載<運算符,當分數(shù)不同時選小的,當分數(shù)相同時,選name的字典序在前的。
    bool operator < (const Student& otherStudent){
        return score != otherStudent.score ? score < otherStudent.score : name < otherStudent.name;
    }
    friend operator << (ostream& os, const Student& student){
        os << "Student: " << student.name << " " << student.score << endl;
    }
};
#endif

運行截圖:


另:

當我這樣修改后,可以驗證選擇排序是不穩(wěn)定的.
Student d[4] = { {"A",95} , {"C",100} , {"B",95} , {"D",90} };

結果是B在A的前面,是不穩(wěn)定的.

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容