56 lines
1.1 KiB
C++
56 lines
1.1 KiB
C++
// 使用函数模版实现对 char 和 int 数组的排序和打印
|
|
#include <iostream>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
|
|
using namespace std;
|
|
|
|
template <typename T>
|
|
void sort(T arr[], int size)
|
|
{
|
|
for (int i = 0; i < size - 1; i++)
|
|
{
|
|
int min = i;
|
|
for (int j = i + 1; j < size; j++)
|
|
{
|
|
if (arr[min] > arr[j])
|
|
{
|
|
min = j;
|
|
}
|
|
}
|
|
if (min != i)
|
|
{
|
|
arr[i] ^= arr[min];
|
|
arr[min] ^= arr[i];
|
|
arr[i] ^= arr[min];
|
|
// T temp = arr[i];
|
|
// arr[i] = arr[min];
|
|
// arr[min] = temp;
|
|
}
|
|
}
|
|
}
|
|
|
|
template <typename T>
|
|
void printArr(T arr[], int size)
|
|
{
|
|
for (int i = 0; i < size; i++)
|
|
cout << arr[i] << " ";
|
|
cout << endl;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
int arr1[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 0};
|
|
char arr2[] = {'a', 'c', 'e', 'G', 'I', 'b', 'd', 'f', 'h', 'j'};
|
|
int size1 = sizeof(arr1) / sizeof(arr1[0]);
|
|
int size2 = sizeof(arr2) / sizeof(arr2[0]);
|
|
|
|
sort(arr1, size1);
|
|
sort(arr2, size2);
|
|
|
|
printArr(arr1, size1);
|
|
printArr(arr2, size2);
|
|
|
|
return 0;
|
|
}
|