c ++ function template of case

1. The function template function using a package sort, can sort the array of different data types.

2. Use sorting algorithm is the selection sort.

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

template<class T>
void mySwap(T& a, T& b) {
    T tmp = a;
    a = b;
    b = tmp;
}

template<class T>
void selectSort(T arr[],int len) {
    for (int i = 0; i < len; i++) {
        int max = i;
        for (int j = i + 1; j < len; j++) {
            if (arr[max]< arr[j]) {
                max = j;
            }
        }
        if (max != i) {
            mySwap(arr[max], arr[i]);
        }

    }
}
template<class T>
void printArr(T arr[],int len) {
    for (int i = 0; i < len; i++) {
        cout << arr[i] <<" ";
    }
    cout << endl;
}
void test() {
    char charArr[] = "badcfe";
    int len = sizeof(charArr) / sizeof(char);
    selectSort(charArr, len);
    printArr(charArr,len);
}
void test2() {
    int intArr[] = {8, 6, 2, 1, 5, 4, 3, 7};
    int len = sizeof(intArr) / sizeof(int);
    selectSort(intArr, len);
    printArr(intArr, len);
}

int main() {
    test();
    test2();
    system("pause");
    return 0;
}

Output:

Guess you like

Origin www.cnblogs.com/xiximayou/p/12104071.html