代码示例:
#include <iostream>
using namespace std;
template <typename T>
void Swap(T& a, T& b)
{
T temp = a;
a = b;
b = temp;
}
//选择排序
template <typename T>
void selectSort(T a[], int size)
{
bool flag = false;
//这里进行了优化
for(int n = size; n > 1 && !flag; n--)
{
flag = true;
int maxIndex = 0;
for(int i = 1; i < n; i++)
{
if(a[maxIndex] <= a[i])
{
maxIndex = i;
}
else
{
flag = false;
}
}
Swap(a[maxIndex], a[n - 1]);
}
}
//冒泡排序
template <typename T>
void bubbleSort(T a[], int size)
{
bool flag = false;
//优化
for(int n = size; n > 1 && !flag; n--)
{
flag = true;
for(int i = 0; i < n - 1; i++)
{
if(a[i] >= a[i + 1])
{
Swap(a[i], a[i + 1]);
flag = false;
}
}
}
}
//插入排序
template <typename T>
void insertSort(T a[], int size)
{
for(int i = 1; i < size; i++)
{
T t = a[i];
int j;
for(j = i - 1; j >= 0 && t < a[j]; j--)
{
a[j + 1] = a[j];
}
a[j + 1] = t;
}
}
int main()
{
int a[9] = {1, 0, 1, 4, 2, 2, 3, 3, 5};
//selectSort(a, 9);
//bubbleSort(a, 9);
insertSort(a, 9);
for(int i = 0; i < 9; i++)
{
cout << a[i] << endl;
}
return 0;
}
运行截图