最简单的C++泛型选择排序代码

#include <iostream>
#include <string>
using namespace std;

template <class T>
void MySwap(T &a, T &b){
    T temp = a;
    a = b;
    b = temp;
}
template <class T, class Func>
void SelectSort(T arr[] , int len, Func swap){
    for(int i=0; i<len; i++){
        int min = i;
        for(int j=i+1; j<len; j++){
            if(arr[j] < arr[min]){
                min = j;
            }
        }
        if(min != i){
            swap(arr[i], arr[min]);
        }
    }
}

template <class T>
void MyPrint(T arr[], int len){
    for(int i=0; i<len; i++){
        cout << arr[i] << ", ";
    }
    cout << endl;
}

int main() {
    int a = 1;
    int b =2;
    MySwap(a, b);
    cout << "a:" <<a <<endl;
    cout << "b:" <<b <<endl;

    int nums[] = {5,6,8,1,3,7,4,2,9};
    int len = sizeof(nums) / sizeof(int);

    MyPrint<int>(nums, len);
    SelectSort<int>(nums, len, MySwap<int>);
    MyPrint<int>(nums, len);

    char ch[] = {'d','a','c','b','g','f','e'};
    int len2 = sizeof(ch) / sizeof(char);

    MyPrint<char>(ch, len2);
    SelectSort<char>(ch, len2, MySwap<char>);
    MyPrint<char>(ch, len2);

    std::cout << "Hello, World!" << std::endl;
    return 0;
}

 

posted @ 2021-01-30 12:40  ziwuxian  阅读(99)  评论(0编辑  收藏  举报