C++实现冒泡排序和选择排序
#include <iostream>
using namespace std;
template<class T>
void bubble_sort(T* a, T n)
{
for(int i=n;i>1;i--)
for (int j = 0; j < i-1; j++)
{
if (a[j] > a[j + 1])
{
int tmp = a[j];
a[j] = a[j + 1];
a[j + 1] = tmp;
}
}
}
template<class T>
void selection_sort(T* a, T n)
{
for (int i = n; i > 1; i--)
{
int max = 0;
int j = 0;
for ( j = 0; j < i; j++)
{
if (a[j] > a[max])
max = j;
}
T tmp = a[j-1];
a[j-1] = a[max];
a[max] = tmp;
}
}
int main()
{
int n[] = { 11,7,8,5,10,2 };
int length = sizeof(n) / sizeof(n[0]);
selection_sort<int>(n, length);
for (int i = 0; i < length; i++)
{
cout << n[i] << ' ';
}
cout << endl;
return 0;
}