1-2使用模板(泛型)编写选择排序算法
为了可以 扩大数据处理的种类,在本程序中使用泛型模板
#include<iostream>
#include<string>
#include"Student.h"
using namespace std;
//选择排序算法
template<class T>
void selectionSort(T arr[], int n)//传入一个数组,n代表数组元素的个数
{
for (int i = 0; i < n; i++)
{
//寻找[i,n)区间里的最小值
int minIndex = i;//定义一个最小值的索引值下标
for (int j = i + 1; j < n; j++)
{
if (arr[minIndex] > arr[j])
{
minIndex = j;
}
}//以上是寻找[i,n)区间里的最小值的过程,并把最小值的索引存在了minIndex中
swap(arr[i], arr[minIndex]);//swap函数是c++标准库里提供的,若使用的是老标准,则需添加#include<algorithm>
}
}
int main()
{
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;
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;
string c[4] = { "D","C","B","A" };
selectionSort(c, 4);
for (int i = 0; i < 4; i++)
{
cout << c[i] << " ";
}
cout << endl;
return 0;
}