泡立ちソートC++テンプレート実装
1340 ワード
泡立ちソートC++テンプレート実装
出力:
3 4 6 8 9 0.2 1.2 11.2 12.6 56.3
#include <iostream>
#include <stdio.h>
using namespace std;
//
template <class T>
void BubSort(T *begin, T *end)
{
T *pi, *pj;
for (pi = end; pi > begin; pi--)
for (pj = begin + 1; pj < pi; pj++)
if (*(pj - 1) > *pj)
{
//
T temp;
temp = *(pj - 1);
*(pj - 1) = *pj;
*pj = temp;
}
}
//
template <class T>
void BubbleSort(T *begin, T *end)
{
T *pi, *pj;
int exchange = 0;//
for (pi = end; pi > begin; pi--)
{
exchange = 0;// 0
for (pj = begin + 1; pj < pi; pj++)
{
if (*(pj - 1) > *pj)
{
//
T temp;
temp = *(pj - 1);
*(pj - 1) = *pj;
*pj = temp;
exchange = 1;// 1
}
}
if (exchange != 1)// , ,
return;
}
}
int main()
{
int a[5] = {3,6,8,4,9};
float b[5] = {1.2, 0.2, 56.3, 11.2, 12.6};
//BubSort(a, a + 5);
//BubSort(b, b + 5);
BubbleSort(a, a + 5);
BubbleSort(b, b + 5);
for (int i = 0; i < 5; i++)
cout << a[i] << "\t";
cout << endl;
for (int i = 0; i < 5; i++)
cout << b[i] << "\t";
getchar();
return 0;
}
出力:
3 4 6 8 9 0.2 1.2 11.2 12.6 56.3